core/iter/traits/iterator.rs
1use super::super::{
2 ArrayChunks, ByRefSized, Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, FlatMap,
3 Flatten, Fuse, Inspect, Intersperse, IntersperseWith, Map, MapWhile, MapWindows, Peekable,
4 Product, Rev, Scan, Skip, SkipWhile, StepBy, Sum, Take, TakeWhile, TrustedRandomAccessNoCoerce,
5 Zip, try_process,
6};
7use super::TrustedLen;
8use crate::array;
9use crate::cmp::{self, KeyAndValue, Ordering};
10use crate::marker::Destruct;
11use crate::num::NonZero;
12use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
13
14fn _assert_is_dyn_compatible(_: &dyn Iterator<Item = ()>) {}
15
16/// A trait for dealing with iterators.
17///
18/// This is the main iterator trait. For more about the concept of iterators
19/// generally, please see the [module-level documentation]. In particular, you
20/// may want to know how to [implement `Iterator`][impl].
21///
22/// [module-level documentation]: crate::iter
23/// [impl]: crate::iter#implementing-iterator
24#[stable(feature = "rust1", since = "1.0.0")]
25#[rustc_on_unimplemented(
26 on(
27 Self = "core::ops::range::RangeTo<Idx>",
28 note = "you might have meant to use a bounded `Range`"
29 ),
30 on(
31 Self = "core::ops::range::RangeToInclusive<Idx>",
32 note = "you might have meant to use a bounded `RangeInclusive`"
33 ),
34 label = "`{Self}` is not an iterator",
35 message = "`{Self}` is not an iterator"
36)]
37#[doc(notable_trait(color = "transparent"))]
38#[lang = "iterator"]
39#[rustc_diagnostic_item = "Iterator"]
40#[must_use = "iterators are lazy and do nothing unless consumed"]
41#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
42pub const trait Iterator {
43 /// The type of the elements being iterated over.
44 #[rustc_diagnostic_item = "IteratorItem"]
45 #[stable(feature = "rust1", since = "1.0.0")]
46 type Item;
47
48 /// Advances the iterator and returns the next value.
49 ///
50 /// Returns [`None`] when iteration is finished. Individual iterator
51 /// implementations may choose to resume iteration, and so calling `next()`
52 /// again may or may not eventually start returning [`Some(Item)`] again at some
53 /// point.
54 ///
55 /// [`Some(Item)`]: Some
56 ///
57 /// # Examples
58 ///
59 /// ```
60 /// let a = [1, 2, 3];
61 ///
62 /// let mut iter = a.into_iter();
63 ///
64 /// // A call to next() returns the next value...
65 /// assert_eq!(Some(1), iter.next());
66 /// assert_eq!(Some(2), iter.next());
67 /// assert_eq!(Some(3), iter.next());
68 ///
69 /// // ... and then None once it's over.
70 /// assert_eq!(None, iter.next());
71 ///
72 /// // More calls may or may not return `None`. Here, they always will.
73 /// assert_eq!(None, iter.next());
74 /// assert_eq!(None, iter.next());
75 /// ```
76 #[lang = "next"]
77 #[stable(feature = "rust1", since = "1.0.0")]
78 fn next(&mut self) -> Option<Self::Item>;
79
80 /// Advances the iterator and returns an array containing the next `N` values.
81 ///
82 /// If there are not enough elements to fill the array then `Err` is returned
83 /// containing an iterator over the remaining elements.
84 ///
85 /// # Examples
86 ///
87 /// Basic usage:
88 ///
89 /// ```
90 /// #![feature(iter_next_chunk)]
91 ///
92 /// let mut iter = "lorem".chars();
93 ///
94 /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']); // N is inferred as 2
95 /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']); // N is inferred as 3
96 /// assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4
97 /// ```
98 ///
99 /// Split a string and get the first three items.
100 ///
101 /// ```
102 /// #![feature(iter_next_chunk)]
103 ///
104 /// let quote = "not all those who wander are lost";
105 /// let [first, second, third] = quote.split_whitespace().next_chunk().unwrap();
106 /// assert_eq!(first, "not");
107 /// assert_eq!(second, "all");
108 /// assert_eq!(third, "those");
109 /// ```
110 #[inline]
111 #[unstable(feature = "iter_next_chunk", issue = "98326")]
112 fn next_chunk<const N: usize>(
113 &mut self,
114 ) -> Result<[Self::Item; N], array::IntoIter<Self::Item, N>>
115 where
116 Self: Sized,
117 {
118 array::iter_next_chunk(self)
119 }
120
121 /// Returns the bounds on the remaining length of the iterator.
122 ///
123 /// Specifically, `size_hint()` returns a tuple where the first element
124 /// is the lower bound, and the second element is the upper bound.
125 ///
126 /// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
127 /// A [`None`] here means that either there is no known upper bound, or the
128 /// upper bound is larger than [`usize`].
129 ///
130 /// # Implementation notes
131 ///
132 /// It is not enforced that an iterator implementation yields the declared
133 /// number of elements. A buggy iterator may yield less than the lower bound
134 /// or more than the upper bound of elements.
135 ///
136 /// `size_hint()` is primarily intended to be used for optimizations such as
137 /// reserving space for the elements of the iterator, but must not be
138 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
139 /// implementation of `size_hint()` should not lead to memory safety
140 /// violations.
141 ///
142 /// That said, the implementation should provide a correct estimation,
143 /// because otherwise it would be a violation of the trait's protocol.
144 ///
145 /// The default implementation returns <code>(0, [None])</code> which is correct for any
146 /// iterator.
147 ///
148 /// # Examples
149 ///
150 /// Basic usage:
151 ///
152 /// ```
153 /// let a = [1, 2, 3];
154 /// let mut iter = a.iter();
155 ///
156 /// assert_eq!((3, Some(3)), iter.size_hint());
157 /// let _ = iter.next();
158 /// assert_eq!((2, Some(2)), iter.size_hint());
159 /// ```
160 ///
161 /// A more complex example:
162 ///
163 /// ```
164 /// // The even numbers in the range of zero to nine.
165 /// let iter = (0..10).filter(|x| x % 2 == 0);
166 ///
167 /// // We might iterate from zero to ten times. Knowing that it's five
168 /// // exactly wouldn't be possible without executing filter().
169 /// assert_eq!((0, Some(10)), iter.size_hint());
170 ///
171 /// // Let's add five more numbers with chain()
172 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
173 ///
174 /// // now both bounds are increased by five
175 /// assert_eq!((5, Some(15)), iter.size_hint());
176 /// ```
177 ///
178 /// Returning `None` for an upper bound:
179 ///
180 /// ```
181 /// // an infinite iterator has no upper bound
182 /// // and the maximum possible lower bound
183 /// let iter = 0..;
184 ///
185 /// assert_eq!((usize::MAX, None), iter.size_hint());
186 /// ```
187 #[inline]
188 #[stable(feature = "rust1", since = "1.0.0")]
189 fn size_hint(&self) -> (usize, Option<usize>) {
190 (0, None)
191 }
192
193 /// Consumes the iterator, counting the number of iterations and returning it.
194 ///
195 /// This method will call [`next`] repeatedly until [`None`] is encountered,
196 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
197 /// called at least once even if the iterator does not have any elements.
198 ///
199 /// [`next`]: Iterator::next
200 ///
201 /// # Overflow Behavior
202 ///
203 /// The method does no guarding against overflows, so counting elements of
204 /// an iterator with more than [`usize::MAX`] elements either produces the
205 /// wrong result or panics. If overflow checks are enabled, a panic is
206 /// guaranteed.
207 ///
208 /// # Panics
209 ///
210 /// This function might panic if the iterator has more than [`usize::MAX`]
211 /// elements.
212 ///
213 /// # Examples
214 ///
215 /// ```
216 /// let a = [1, 2, 3];
217 /// assert_eq!(a.iter().count(), 3);
218 ///
219 /// let a = [1, 2, 3, 4, 5];
220 /// assert_eq!(a.iter().count(), 5);
221 /// ```
222 #[inline]
223 #[stable(feature = "rust1", since = "1.0.0")]
224 fn count(self) -> usize
225 where
226 Self: Sized + [const] Destruct,
227 Self::Item: [const] Destruct,
228 {
229 self.fold(
230 0,
231 #[rustc_inherit_overflow_checks]
232 const |accum, _elem| accum + 1,
233 )
234 }
235
236 /// Consumes the iterator, returning the last element.
237 ///
238 /// This method will evaluate the iterator until it returns [`None`]. While
239 /// doing so, it keeps track of the current element. After [`None`] is
240 /// returned, `last()` will then return the last element it saw.
241 ///
242 /// # Panics
243 ///
244 /// This function might panic if the iterator is infinite.
245 ///
246 /// # Examples
247 ///
248 /// ```
249 /// let a = [1, 2, 3];
250 /// assert_eq!(a.into_iter().last(), Some(3));
251 ///
252 /// let a = [1, 2, 3, 4, 5];
253 /// assert_eq!(a.into_iter().last(), Some(5));
254 /// ```
255 #[inline]
256 #[stable(feature = "rust1", since = "1.0.0")]
257 fn last(self) -> Option<Self::Item>
258 where
259 Self: Sized + [const] Destruct,
260 Self::Item: [const] Destruct,
261 {
262 #[inline]
263 #[rustc_const_unstable(feature = "const_destruct", issue = "133214")]
264 const fn some<T>(_: Option<T>, x: T) -> Option<T>
265 where
266 T: [const] Destruct,
267 {
268 Some(x)
269 }
270
271 self.fold(None, some)
272 }
273
274 /// Advances the iterator by `n` elements.
275 ///
276 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
277 /// times until [`None`] is encountered.
278 ///
279 /// `advance_by(n)` will return `Ok(())` if the iterator successfully advances by
280 /// `n` elements, or a `Err(NonZero<usize>)` with value `k` if [`None`] is encountered,
281 /// where `k` is remaining number of steps that could not be advanced because the iterator ran out.
282 /// If `self` is empty and `n` is non-zero, then this returns `Err(n)`.
283 /// Otherwise, `k` is always less than `n`.
284 ///
285 /// Calling `advance_by(0)` can do meaningful work, for example [`Flatten`]
286 /// can advance its outer iterator until it finds an inner iterator that is not empty, which
287 /// then often allows it to return a more accurate `size_hint()` than in its initial state.
288 ///
289 /// [`Flatten`]: crate::iter::Flatten
290 /// [`next`]: Iterator::next
291 ///
292 /// # Examples
293 ///
294 /// ```
295 /// #![feature(iter_advance_by)]
296 ///
297 /// use std::num::NonZero;
298 ///
299 /// let a = [1, 2, 3, 4];
300 /// let mut iter = a.into_iter();
301 ///
302 /// assert_eq!(iter.advance_by(2), Ok(()));
303 /// assert_eq!(iter.next(), Some(3));
304 /// assert_eq!(iter.advance_by(0), Ok(()));
305 /// assert_eq!(iter.advance_by(100), Err(NonZero::new(99).unwrap())); // only `4` was skipped
306 /// ```
307 #[inline]
308 #[unstable(feature = "iter_advance_by", issue = "77404")]
309 #[rustc_non_const_trait_method]
310 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
311 /// Helper trait to specialize `advance_by` via `try_fold` for `Sized` iterators.
312 trait SpecAdvanceBy {
313 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>;
314 }
315
316 impl<I: Iterator + ?Sized> SpecAdvanceBy for I {
317 default fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
318 for i in 0..n {
319 if self.next().is_none() {
320 // SAFETY: `i` is always less than `n`.
321 return Err(unsafe { NonZero::new_unchecked(n - i) });
322 }
323 }
324 Ok(())
325 }
326 }
327
328 impl<I: Iterator> SpecAdvanceBy for I {
329 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
330 let Some(n) = NonZero::new(n) else {
331 return Ok(());
332 };
333
334 let res = self.try_fold(n, |n, _| NonZero::new(n.get() - 1));
335
336 match res {
337 None => Ok(()),
338 Some(n) => Err(n),
339 }
340 }
341 }
342
343 self.spec_advance_by(n)
344 }
345
346 /// Returns the `n`th element of the iterator.
347 ///
348 /// Like most indexing operations, the count starts from zero, so `nth(0)`
349 /// returns the first value, `nth(1)` the second, and so on.
350 ///
351 /// Note that all preceding elements, as well as the returned element, will be
352 /// consumed from the iterator. That means that the preceding elements will be
353 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
354 /// will return different elements.
355 ///
356 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
357 /// iterator.
358 ///
359 /// # Examples
360 ///
361 /// Basic usage:
362 ///
363 /// ```
364 /// let a = [1, 2, 3];
365 /// assert_eq!(a.into_iter().nth(1), Some(2));
366 /// ```
367 ///
368 /// Calling `nth()` multiple times doesn't rewind the iterator:
369 ///
370 /// ```
371 /// let a = [1, 2, 3];
372 ///
373 /// let mut iter = a.into_iter();
374 ///
375 /// assert_eq!(iter.nth(1), Some(2));
376 /// assert_eq!(iter.nth(1), None);
377 /// ```
378 ///
379 /// Returning `None` if there are less than `n + 1` elements:
380 ///
381 /// ```
382 /// let a = [1, 2, 3];
383 /// assert_eq!(a.into_iter().nth(10), None);
384 /// ```
385 #[inline]
386 #[stable(feature = "rust1", since = "1.0.0")]
387 #[rustc_diagnostic_item = "iter_nth"]
388 #[rustc_non_const_trait_method]
389 fn nth(&mut self, n: usize) -> Option<Self::Item> {
390 self.advance_by(n).ok()?;
391 self.next()
392 }
393
394 /// Creates an iterator starting at the same point, but stepping by
395 /// the given amount at each iteration.
396 ///
397 /// Note 1: The first element of the iterator will always be returned,
398 /// regardless of the step given.
399 ///
400 /// Note 2: The time at which ignored elements are pulled is not fixed.
401 /// `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`,
402 /// `self.nth(step-1)`, …, but is also free to behave like the sequence
403 /// `advance_n_and_return_first(&mut self, step)`,
404 /// `advance_n_and_return_first(&mut self, step)`, …
405 /// Which way is used may change for some iterators for performance reasons.
406 /// The second way will advance the iterator earlier and may consume more items.
407 ///
408 /// `advance_n_and_return_first` is the equivalent of:
409 /// ```
410 /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
411 /// where
412 /// I: Iterator,
413 /// {
414 /// let next = iter.next();
415 /// if n > 1 {
416 /// iter.nth(n - 2);
417 /// }
418 /// next
419 /// }
420 /// ```
421 ///
422 /// # Panics
423 ///
424 /// The method will panic if the given step is `0`.
425 ///
426 /// # Examples
427 ///
428 /// ```
429 /// let a = [0, 1, 2, 3, 4, 5];
430 /// let mut iter = a.into_iter().step_by(2);
431 ///
432 /// assert_eq!(iter.next(), Some(0));
433 /// assert_eq!(iter.next(), Some(2));
434 /// assert_eq!(iter.next(), Some(4));
435 /// assert_eq!(iter.next(), None);
436 /// ```
437 #[inline]
438 #[stable(feature = "iterator_step_by", since = "1.28.0")]
439 #[rustc_non_const_trait_method]
440 #[rustc_diagnostic_item = "iter_step_by"]
441 fn step_by(self, step: usize) -> StepBy<Self>
442 where
443 Self: Sized,
444 {
445 StepBy::new(self, step)
446 }
447
448 /// Takes two iterators and creates a new iterator over both in sequence.
449 ///
450 /// `chain()` will return a new iterator which will first iterate over
451 /// values from the first iterator and then over values from the second
452 /// iterator.
453 ///
454 /// In other words, it links two iterators together, in a chain. 🔗
455 ///
456 /// [`once`] is commonly used to adapt a single value into a chain of
457 /// other kinds of iteration.
458 ///
459 /// # Examples
460 ///
461 /// Basic usage:
462 ///
463 /// ```
464 /// let s1 = "abc".chars();
465 /// let s2 = "def".chars();
466 ///
467 /// let mut iter = s1.chain(s2);
468 ///
469 /// assert_eq!(iter.next(), Some('a'));
470 /// assert_eq!(iter.next(), Some('b'));
471 /// assert_eq!(iter.next(), Some('c'));
472 /// assert_eq!(iter.next(), Some('d'));
473 /// assert_eq!(iter.next(), Some('e'));
474 /// assert_eq!(iter.next(), Some('f'));
475 /// assert_eq!(iter.next(), None);
476 /// ```
477 ///
478 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
479 /// anything that can be converted into an [`Iterator`], not just an
480 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
481 /// [`IntoIterator`], and so can be passed to `chain()` directly:
482 ///
483 /// ```
484 /// let a1 = [1, 2, 3];
485 /// let a2 = [4, 5, 6];
486 ///
487 /// let mut iter = a1.into_iter().chain(a2);
488 ///
489 /// assert_eq!(iter.next(), Some(1));
490 /// assert_eq!(iter.next(), Some(2));
491 /// assert_eq!(iter.next(), Some(3));
492 /// assert_eq!(iter.next(), Some(4));
493 /// assert_eq!(iter.next(), Some(5));
494 /// assert_eq!(iter.next(), Some(6));
495 /// assert_eq!(iter.next(), None);
496 /// ```
497 ///
498 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
499 ///
500 /// ```
501 /// #[cfg(windows)]
502 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
503 /// use std::os::windows::ffi::OsStrExt;
504 /// s.encode_wide().chain(std::iter::once(0)).collect()
505 /// }
506 /// ```
507 ///
508 /// [`once`]: crate::iter::once
509 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
510 #[inline]
511 #[stable(feature = "rust1", since = "1.0.0")]
512 #[rustc_diagnostic_item = "iter_chain"]
513 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
514 where
515 Self: Sized,
516 U: [const] IntoIterator<Item = Self::Item>,
517 {
518 Chain::new(self, other.into_iter())
519 }
520
521 /// 'Zips up' two iterators into a single iterator of pairs.
522 ///
523 /// `zip()` returns a new iterator that will iterate over two other
524 /// iterators, returning a tuple where the first element comes from the
525 /// first iterator, and the second element comes from the second iterator.
526 ///
527 /// In other words, it zips two iterators together, into a single one.
528 ///
529 /// If either iterator returns [`None`], [`next`] from the zipped iterator
530 /// will return [`None`].
531 /// If the zipped iterator has no more elements to return then each further attempt to advance
532 /// it will first try to advance the first iterator at most one time and if it still yielded an item
533 /// try to advance the second iterator at most one time.
534 ///
535 /// To 'undo' the result of zipping up two iterators, see [`unzip`].
536 ///
537 /// [`unzip`]: Iterator::unzip
538 ///
539 /// # Examples
540 ///
541 /// Basic usage:
542 ///
543 /// ```
544 /// let s1 = "abc".chars();
545 /// let s2 = "def".chars();
546 ///
547 /// let mut iter = s1.zip(s2);
548 ///
549 /// assert_eq!(iter.next(), Some(('a', 'd')));
550 /// assert_eq!(iter.next(), Some(('b', 'e')));
551 /// assert_eq!(iter.next(), Some(('c', 'f')));
552 /// assert_eq!(iter.next(), None);
553 /// ```
554 ///
555 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
556 /// anything that can be converted into an [`Iterator`], not just an
557 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
558 /// [`IntoIterator`], and so can be passed to `zip()` directly:
559 ///
560 /// ```
561 /// let a1 = [1, 2, 3];
562 /// let a2 = [4, 5, 6];
563 ///
564 /// let mut iter = a1.into_iter().zip(a2);
565 ///
566 /// assert_eq!(iter.next(), Some((1, 4)));
567 /// assert_eq!(iter.next(), Some((2, 5)));
568 /// assert_eq!(iter.next(), Some((3, 6)));
569 /// assert_eq!(iter.next(), None);
570 /// ```
571 ///
572 /// `zip()` is often used to zip an infinite iterator to a finite one.
573 /// This works because the finite iterator will eventually return [`None`],
574 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
575 ///
576 /// ```
577 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
578 ///
579 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
580 ///
581 /// assert_eq!((0, 'f'), enumerate[0]);
582 /// assert_eq!((0, 'f'), zipper[0]);
583 ///
584 /// assert_eq!((1, 'o'), enumerate[1]);
585 /// assert_eq!((1, 'o'), zipper[1]);
586 ///
587 /// assert_eq!((2, 'o'), enumerate[2]);
588 /// assert_eq!((2, 'o'), zipper[2]);
589 /// ```
590 ///
591 /// If both iterators have roughly equivalent syntax, it may be more readable to use [`zip`]:
592 ///
593 /// ```
594 /// use std::iter::zip;
595 ///
596 /// let a = [1, 2, 3];
597 /// let b = [2, 3, 4];
598 ///
599 /// let mut zipped = zip(
600 /// a.into_iter().map(|x| x * 2).skip(1),
601 /// b.into_iter().map(|x| x * 2).skip(1),
602 /// );
603 ///
604 /// assert_eq!(zipped.next(), Some((4, 6)));
605 /// assert_eq!(zipped.next(), Some((6, 8)));
606 /// assert_eq!(zipped.next(), None);
607 /// ```
608 ///
609 /// compared to:
610 ///
611 /// ```
612 /// # let a = [1, 2, 3];
613 /// # let b = [2, 3, 4];
614 /// #
615 /// let mut zipped = a
616 /// .into_iter()
617 /// .map(|x| x * 2)
618 /// .skip(1)
619 /// .zip(b.into_iter().map(|x| x * 2).skip(1));
620 /// #
621 /// # assert_eq!(zipped.next(), Some((4, 6)));
622 /// # assert_eq!(zipped.next(), Some((6, 8)));
623 /// # assert_eq!(zipped.next(), None);
624 /// ```
625 ///
626 /// [`enumerate`]: Iterator::enumerate
627 /// [`next`]: Iterator::next
628 /// [`zip`]: crate::iter::zip
629 #[inline]
630 #[stable(feature = "rust1", since = "1.0.0")]
631 #[rustc_non_const_trait_method]
632 #[rustc_diagnostic_item = "iter_zip"]
633 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
634 where
635 Self: Sized,
636 U: IntoIterator,
637 {
638 Zip::new(self, other.into_iter())
639 }
640
641 /// Creates a new iterator which places a copy of `separator` between items
642 /// of the original iterator.
643 ///
644 /// Specifically on fused iterators, it is guaranteed that the new iterator
645 /// places a copy of `separator` between *adjacent* `Some(_)` items. For non-fused iterators,
646 /// it is guaranteed that [`intersperse`] will create a new iterator that places a copy
647 /// of `separator` between `Some(_)` items, particularly just right before the subsequent
648 /// `Some(_)` item.
649 ///
650 /// For example, consider the following non-fused iterator:
651 ///
652 /// ```text
653 /// Some(1) -> Some(2) -> None -> Some(3) -> Some(4) -> ...
654 /// ```
655 ///
656 /// If this non-fused iterator were to be interspersed with `0`,
657 /// then the interspersed iterator will produce:
658 ///
659 /// ```text
660 /// Some(1) -> Some(0) -> Some(2) -> None -> Some(0) -> Some(3) -> Some(0) ->
661 /// Some(4) -> ...
662 /// ```
663 ///
664 /// In case `separator` does not implement [`Clone`] or needs to be
665 /// computed every time, use [`intersperse_with`].
666 ///
667 /// # Examples
668 ///
669 /// Basic usage:
670 ///
671 /// ```
672 /// #![feature(iter_intersperse)]
673 ///
674 /// let mut a = [0, 1, 2].into_iter().intersperse(100);
675 /// assert_eq!(a.next(), Some(0)); // The first element from `a`.
676 /// assert_eq!(a.next(), Some(100)); // The separator.
677 /// assert_eq!(a.next(), Some(1)); // The next element from `a`.
678 /// assert_eq!(a.next(), Some(100)); // The separator.
679 /// assert_eq!(a.next(), Some(2)); // The last element from `a`.
680 /// assert_eq!(a.next(), None); // The iterator is finished.
681 /// ```
682 ///
683 /// `intersperse` can be very useful to join an iterator's items using a common element:
684 /// ```
685 /// #![feature(iter_intersperse)]
686 ///
687 /// let words = ["Hello", "World", "!"];
688 /// let hello: String = words.into_iter().intersperse(" ").collect();
689 /// assert_eq!(hello, "Hello World !");
690 /// ```
691 ///
692 /// [`Clone`]: crate::clone::Clone
693 /// [`intersperse`]: Iterator::intersperse
694 /// [`intersperse_with`]: Iterator::intersperse_with
695 #[inline]
696 #[unstable(feature = "iter_intersperse", issue = "79524")]
697 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
698 where
699 Self: Sized,
700 Self::Item: Clone,
701 {
702 Intersperse::new(self, separator)
703 }
704
705 /// Creates a new iterator which places an item generated by `separator`
706 /// between items of the original iterator.
707 ///
708 /// Specifically on fused iterators, it is guaranteed that the new iterator
709 /// places an item generated by `separator` between adjacent `Some(_)` items.
710 /// For non-fused iterators, it is guaranteed that [`intersperse_with`] will
711 /// create a new iterator that places an item generated by `separator` between `Some(_)`
712 /// items, particularly just right before the subsequent `Some(_)` item.
713 ///
714 /// For example, consider the following non-fused iterator:
715 ///
716 /// ```text
717 /// Some(1) -> Some(2) -> None -> Some(3) -> Some(4) -> ...
718 /// ```
719 ///
720 /// If this non-fused iterator were to be interspersed with a `separator` closure
721 /// that returns `0` repeatedly, the interspersed iterator will produce:
722 ///
723 /// ```text
724 /// Some(1) -> Some(0) -> Some(2) -> None -> Some(0) -> Some(3) -> Some(0) ->
725 /// Some(4) -> ...
726 /// ```
727 ///
728 /// The `separator` closure will be called exactly once each time an item
729 /// is placed between two adjacent items from the underlying iterator;
730 /// specifically, the closure is not called if the underlying iterator yields
731 /// less than two items and after the last item is yielded.
732 ///
733 /// If the iterator's item implements [`Clone`], it may be easier to use
734 /// [`intersperse`].
735 ///
736 /// # Examples
737 ///
738 /// Basic usage:
739 ///
740 /// ```
741 /// #![feature(iter_intersperse)]
742 ///
743 /// #[derive(PartialEq, Debug)]
744 /// struct NotClone(usize);
745 ///
746 /// let v = [NotClone(0), NotClone(1), NotClone(2)];
747 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
748 ///
749 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
750 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
751 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
752 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
753 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from `v`.
754 /// assert_eq!(it.next(), None); // The iterator is finished.
755 /// ```
756 ///
757 /// `intersperse_with` can be used in situations where the separator needs
758 /// to be computed:
759 /// ```
760 /// #![feature(iter_intersperse)]
761 ///
762 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
763 ///
764 /// // The closure mutably borrows its context to generate an item.
765 /// let mut happy_emojis = [" ❤️ ", " 😀 "].into_iter();
766 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
767 ///
768 /// let result = src.intersperse_with(separator).collect::<String>();
769 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
770 /// ```
771 /// [`Clone`]: crate::clone::Clone
772 /// [`intersperse`]: Iterator::intersperse
773 /// [`intersperse_with`]: Iterator::intersperse_with
774 #[inline]
775 #[unstable(feature = "iter_intersperse", issue = "79524")]
776 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
777 where
778 Self: Sized,
779 G: FnMut() -> Self::Item,
780 {
781 IntersperseWith::new(self, separator)
782 }
783
784 /// Takes a closure and creates an iterator which calls that closure on each
785 /// element.
786 ///
787 /// `map()` transforms one iterator into another, by means of its argument:
788 /// something that implements [`FnMut`]. It produces a new iterator which
789 /// calls this closure on each element of the original iterator.
790 ///
791 /// If you are good at thinking in types, you can think of `map()` like this:
792 /// If you have an iterator that gives you elements of some type `A`, and
793 /// you want an iterator of some other type `B`, you can use `map()`,
794 /// passing a closure that takes an `A` and returns a `B`.
795 ///
796 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
797 /// lazy, it is best used when you're already working with other iterators.
798 /// If you're doing some sort of looping for a side effect, it's considered
799 /// more idiomatic to use [`for`] than `map()`.
800 ///
801 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
802 ///
803 /// # Examples
804 ///
805 /// Basic usage:
806 ///
807 /// ```
808 /// let a = [1, 2, 3];
809 ///
810 /// let mut iter = a.iter().map(|x| 2 * x);
811 ///
812 /// assert_eq!(iter.next(), Some(2));
813 /// assert_eq!(iter.next(), Some(4));
814 /// assert_eq!(iter.next(), Some(6));
815 /// assert_eq!(iter.next(), None);
816 /// ```
817 ///
818 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
819 ///
820 /// ```
821 /// # #![allow(unused_must_use)]
822 /// // don't do this:
823 /// (0..5).map(|x| println!("{x}"));
824 ///
825 /// // it won't even execute, as it is lazy. Rust will warn you about this.
826 ///
827 /// // Instead, use a for-loop:
828 /// for x in 0..5 {
829 /// println!("{x}");
830 /// }
831 /// ```
832 #[rustc_diagnostic_item = "IteratorMap"]
833 #[inline]
834 #[stable(feature = "rust1", since = "1.0.0")]
835 fn map<B, F>(self, f: F) -> Map<Self, F>
836 where
837 Self: Sized,
838 F: FnMut(Self::Item) -> B,
839 {
840 Map::new(self, f)
841 }
842
843 /// Calls a closure on each element of an iterator.
844 ///
845 /// This is equivalent to using a [`for`] loop on the iterator, although
846 /// `break` and `continue` are not possible from a closure. It's generally
847 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
848 /// when processing items at the end of longer iterator chains. In some
849 /// cases `for_each` may also be faster than a loop, because it will use
850 /// internal iteration on adapters like `Chain`.
851 ///
852 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
853 ///
854 /// # Examples
855 ///
856 /// Basic usage:
857 ///
858 /// ```
859 /// use std::sync::mpsc::channel;
860 ///
861 /// let (tx, rx) = channel();
862 /// (0..5).map(|x| x * 2 + 1)
863 /// .for_each(move |x| tx.send(x).unwrap());
864 ///
865 /// let v: Vec<_> = rx.iter().collect();
866 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
867 /// ```
868 ///
869 /// For such a small example, a `for` loop may be cleaner, but `for_each`
870 /// might be preferable to keep a functional style with longer iterators:
871 ///
872 /// ```
873 /// (0..5).flat_map(|x| (x * 100)..(x * 110))
874 /// .enumerate()
875 /// .filter(|&(i, x)| (i + x) % 3 == 0)
876 /// .for_each(|(i, x)| println!("{i}:{x}"));
877 /// ```
878 #[inline]
879 #[stable(feature = "iterator_for_each", since = "1.21.0")]
880 #[rustc_non_const_trait_method]
881 #[rustc_diagnostic_item = "iter_for_each"]
882 fn for_each<F>(self, f: F)
883 where
884 Self: Sized,
885 F: FnMut(Self::Item),
886 {
887 #[inline]
888 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
889 move |(), item| f(item)
890 }
891
892 self.fold((), call(f));
893 }
894
895 /// Creates an iterator which uses a closure to determine if an element
896 /// should be yielded.
897 ///
898 /// Given an element the closure must return `true` or `false`. The returned
899 /// iterator will yield only the elements for which the closure returns
900 /// `true`.
901 ///
902 /// # Examples
903 ///
904 /// Basic usage:
905 ///
906 /// ```
907 /// let a = [0i32, 1, 2];
908 ///
909 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
910 ///
911 /// assert_eq!(iter.next(), Some(1));
912 /// assert_eq!(iter.next(), Some(2));
913 /// assert_eq!(iter.next(), None);
914 /// ```
915 ///
916 /// Because the closure passed to `filter()` takes a reference, and many
917 /// iterators iterate over references, this leads to a possibly confusing
918 /// situation, where the type of the closure is a double reference:
919 ///
920 /// ```
921 /// let s = &[0, 1, 2];
922 ///
923 /// let mut iter = s.iter().filter(|x| **x > 1); // needs two *s!
924 ///
925 /// assert_eq!(iter.next(), Some(&2));
926 /// assert_eq!(iter.next(), None);
927 /// ```
928 ///
929 /// It's common to instead use destructuring on the argument to strip away one:
930 ///
931 /// ```
932 /// let s = &[0, 1, 2];
933 ///
934 /// let mut iter = s.iter().filter(|&x| *x > 1); // both & and *
935 ///
936 /// assert_eq!(iter.next(), Some(&2));
937 /// assert_eq!(iter.next(), None);
938 /// ```
939 ///
940 /// or both:
941 ///
942 /// ```
943 /// let s = &[0, 1, 2];
944 ///
945 /// let mut iter = s.iter().filter(|&&x| x > 1); // two &s
946 ///
947 /// assert_eq!(iter.next(), Some(&2));
948 /// assert_eq!(iter.next(), None);
949 /// ```
950 ///
951 /// of these layers.
952 ///
953 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
954 #[inline]
955 #[stable(feature = "rust1", since = "1.0.0")]
956 #[rustc_diagnostic_item = "iter_filter"]
957 fn filter<P>(self, predicate: P) -> Filter<Self, P>
958 where
959 Self: Sized,
960 P: FnMut(&Self::Item) -> bool,
961 {
962 Filter::new(self, predicate)
963 }
964
965 /// Creates an iterator that both filters and maps.
966 ///
967 /// The returned iterator yields only the `value`s for which the supplied
968 /// closure returns `Some(value)`.
969 ///
970 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
971 /// concise. The example below shows how a `map().filter().map()` can be
972 /// shortened to a single call to `filter_map`.
973 ///
974 /// [`filter`]: Iterator::filter
975 /// [`map`]: Iterator::map
976 ///
977 /// # Examples
978 ///
979 /// Basic usage:
980 ///
981 /// ```
982 /// let a = ["1", "two", "NaN", "four", "5"];
983 ///
984 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
985 ///
986 /// assert_eq!(iter.next(), Some(1));
987 /// assert_eq!(iter.next(), Some(5));
988 /// assert_eq!(iter.next(), None);
989 /// ```
990 ///
991 /// Here's the same example, but with [`filter`] and [`map`]:
992 ///
993 /// ```
994 /// let a = ["1", "two", "NaN", "four", "5"];
995 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
996 /// assert_eq!(iter.next(), Some(1));
997 /// assert_eq!(iter.next(), Some(5));
998 /// assert_eq!(iter.next(), None);
999 /// ```
1000 #[inline]
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 #[rustc_diagnostic_item = "iter_filter_map"]
1003 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
1004 where
1005 Self: Sized,
1006 F: FnMut(Self::Item) -> Option<B>,
1007 {
1008 FilterMap::new(self, f)
1009 }
1010
1011 /// Creates an iterator which gives the current iteration count as well as
1012 /// the next value.
1013 ///
1014 /// The iterator returned yields pairs `(i, val)`, where `i` is the
1015 /// current index of iteration and `val` is the value returned by the
1016 /// iterator.
1017 ///
1018 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
1019 /// different sized integer, the [`zip`] function provides similar
1020 /// functionality.
1021 ///
1022 /// # Overflow Behavior
1023 ///
1024 /// The method does no guarding against overflows, so enumerating more than
1025 /// [`usize::MAX`] elements either produces the wrong result or panics. If
1026 /// overflow checks are enabled, a panic is guaranteed.
1027 ///
1028 /// # Panics
1029 ///
1030 /// The returned iterator might panic if the to-be-returned index would
1031 /// overflow a [`usize`].
1032 ///
1033 /// [`zip`]: Iterator::zip
1034 ///
1035 /// # Examples
1036 ///
1037 /// ```
1038 /// let a = ['a', 'b', 'c'];
1039 ///
1040 /// let mut iter = a.into_iter().enumerate();
1041 ///
1042 /// assert_eq!(iter.next(), Some((0, 'a')));
1043 /// assert_eq!(iter.next(), Some((1, 'b')));
1044 /// assert_eq!(iter.next(), Some((2, 'c')));
1045 /// assert_eq!(iter.next(), None);
1046 /// ```
1047 #[inline]
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 #[rustc_diagnostic_item = "enumerate_method"]
1050 fn enumerate(self) -> Enumerate<Self>
1051 where
1052 Self: Sized,
1053 {
1054 Enumerate::new(self)
1055 }
1056
1057 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
1058 /// to look at the next element of the iterator without consuming it. See
1059 /// their documentation for more information.
1060 ///
1061 /// Note that the underlying iterator is still advanced when [`peek`] or
1062 /// [`peek_mut`] are called for the first time: In order to retrieve the
1063 /// next element, [`next`] is called on the underlying iterator, hence any
1064 /// side effects (i.e. anything other than fetching the next value) of
1065 /// the [`next`] method will occur.
1066 ///
1067 ///
1068 /// # Examples
1069 ///
1070 /// Basic usage:
1071 ///
1072 /// ```
1073 /// let xs = [1, 2, 3];
1074 ///
1075 /// let mut iter = xs.into_iter().peekable();
1076 ///
1077 /// // peek() lets us see into the future
1078 /// assert_eq!(iter.peek(), Some(&1));
1079 /// assert_eq!(iter.next(), Some(1));
1080 ///
1081 /// assert_eq!(iter.next(), Some(2));
1082 ///
1083 /// // we can peek() multiple times, the iterator won't advance
1084 /// assert_eq!(iter.peek(), Some(&3));
1085 /// assert_eq!(iter.peek(), Some(&3));
1086 ///
1087 /// assert_eq!(iter.next(), Some(3));
1088 ///
1089 /// // after the iterator is finished, so is peek()
1090 /// assert_eq!(iter.peek(), None);
1091 /// assert_eq!(iter.next(), None);
1092 /// ```
1093 ///
1094 /// Using [`peek_mut`] to mutate the next item without advancing the
1095 /// iterator:
1096 ///
1097 /// ```
1098 /// let xs = [1, 2, 3];
1099 ///
1100 /// let mut iter = xs.into_iter().peekable();
1101 ///
1102 /// // `peek_mut()` lets us see into the future
1103 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1104 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1105 /// assert_eq!(iter.next(), Some(1));
1106 ///
1107 /// if let Some(p) = iter.peek_mut() {
1108 /// assert_eq!(*p, 2);
1109 /// // put a value into the iterator
1110 /// *p = 1000;
1111 /// }
1112 ///
1113 /// // The value reappears as the iterator continues
1114 /// assert_eq!(iter.collect::<Vec<_>>(), vec![1000, 3]);
1115 /// ```
1116 /// [`peek`]: Peekable::peek
1117 /// [`peek_mut`]: Peekable::peek_mut
1118 /// [`next`]: Iterator::next
1119 #[inline]
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 fn peekable(self) -> Peekable<Self>
1122 where
1123 Self: Sized,
1124 {
1125 Peekable::new(self)
1126 }
1127
1128 /// Creates an iterator that [`skip`]s elements based on a predicate.
1129 ///
1130 /// [`skip`]: Iterator::skip
1131 ///
1132 /// `skip_while()` takes a closure as an argument. It will call this
1133 /// closure on each element of the iterator, and ignore elements
1134 /// until it returns `false`.
1135 ///
1136 /// After `false` is returned, `skip_while()`'s job is over, and the
1137 /// rest of the elements are yielded.
1138 ///
1139 /// # Examples
1140 ///
1141 /// Basic usage:
1142 ///
1143 /// ```
1144 /// let a = [-1i32, 0, 1];
1145 ///
1146 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
1147 ///
1148 /// assert_eq!(iter.next(), Some(0));
1149 /// assert_eq!(iter.next(), Some(1));
1150 /// assert_eq!(iter.next(), None);
1151 /// ```
1152 ///
1153 /// Because the closure passed to `skip_while()` takes a reference, and many
1154 /// iterators iterate over references, this leads to a possibly confusing
1155 /// situation, where the type of the closure argument is a double reference:
1156 ///
1157 /// ```
1158 /// let s = &[-1, 0, 1];
1159 ///
1160 /// let mut iter = s.iter().skip_while(|x| **x < 0); // need two *s!
1161 ///
1162 /// assert_eq!(iter.next(), Some(&0));
1163 /// assert_eq!(iter.next(), Some(&1));
1164 /// assert_eq!(iter.next(), None);
1165 /// ```
1166 ///
1167 /// Stopping after an initial `false`:
1168 ///
1169 /// ```
1170 /// let a = [-1, 0, 1, -2];
1171 ///
1172 /// let mut iter = a.into_iter().skip_while(|&x| x < 0);
1173 ///
1174 /// assert_eq!(iter.next(), Some(0));
1175 /// assert_eq!(iter.next(), Some(1));
1176 ///
1177 /// // while this would have been false, since we already got a false,
1178 /// // skip_while() isn't used any more
1179 /// assert_eq!(iter.next(), Some(-2));
1180 ///
1181 /// assert_eq!(iter.next(), None);
1182 /// ```
1183 #[inline]
1184 #[doc(alias = "drop_while")]
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 #[rustc_diagnostic_item = "iter_skip_while"]
1187 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1188 where
1189 Self: Sized,
1190 P: FnMut(&Self::Item) -> bool,
1191 {
1192 SkipWhile::new(self, predicate)
1193 }
1194
1195 /// Creates an iterator that yields elements based on a predicate.
1196 ///
1197 /// `take_while()` takes a closure as an argument. It will call this
1198 /// closure on each element of the iterator, and yield elements
1199 /// while it returns `true`.
1200 ///
1201 /// After `false` is returned, `take_while()`'s job is over, and the
1202 /// rest of the elements are ignored.
1203 ///
1204 /// # Examples
1205 ///
1206 /// Basic usage:
1207 ///
1208 /// ```
1209 /// let a = [-1i32, 0, 1];
1210 ///
1211 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1212 ///
1213 /// assert_eq!(iter.next(), Some(-1));
1214 /// assert_eq!(iter.next(), None);
1215 /// ```
1216 ///
1217 /// Because the closure passed to `take_while()` takes a reference, and many
1218 /// iterators iterate over references, this leads to a possibly confusing
1219 /// situation, where the type of the closure is a double reference:
1220 ///
1221 /// ```
1222 /// let s = &[-1, 0, 1];
1223 ///
1224 /// let mut iter = s.iter().take_while(|x| **x < 0); // need two *s!
1225 ///
1226 /// assert_eq!(iter.next(), Some(&-1));
1227 /// assert_eq!(iter.next(), None);
1228 /// ```
1229 ///
1230 /// Stopping after an initial `false`:
1231 ///
1232 /// ```
1233 /// let a = [-1, 0, 1, -2];
1234 ///
1235 /// let mut iter = a.into_iter().take_while(|&x| x < 0);
1236 ///
1237 /// assert_eq!(iter.next(), Some(-1));
1238 ///
1239 /// // We have more elements that are less than zero, but since we already
1240 /// // got a false, take_while() ignores the remaining elements.
1241 /// assert_eq!(iter.next(), None);
1242 /// ```
1243 ///
1244 /// Because `take_while()` needs to look at the value in order to see if it
1245 /// should be included or not, consuming iterators will see that it is
1246 /// removed:
1247 ///
1248 /// ```
1249 /// let a = [1, 2, 3, 4];
1250 /// let mut iter = a.into_iter();
1251 ///
1252 /// let result: Vec<i32> = iter.by_ref().take_while(|&n| n != 3).collect();
1253 ///
1254 /// assert_eq!(result, [1, 2]);
1255 ///
1256 /// let result: Vec<i32> = iter.collect();
1257 ///
1258 /// assert_eq!(result, [4]);
1259 /// ```
1260 ///
1261 /// The `3` is no longer there, because it was consumed in order to see if
1262 /// the iteration should stop, but wasn't placed back into the iterator.
1263 #[inline]
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 #[rustc_diagnostic_item = "take_while"]
1266 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1267 where
1268 Self: Sized,
1269 P: FnMut(&Self::Item) -> bool,
1270 {
1271 TakeWhile::new(self, predicate)
1272 }
1273
1274 /// Creates an iterator that both yields elements based on a predicate and maps.
1275 ///
1276 /// `map_while()` takes a closure as an argument. It will call this
1277 /// closure on each element of the iterator, and yield elements
1278 /// while it returns [`Some(_)`][`Some`].
1279 ///
1280 /// # Examples
1281 ///
1282 /// Basic usage:
1283 ///
1284 /// ```
1285 /// let a = [-1i32, 4, 0, 1];
1286 ///
1287 /// let mut iter = a.into_iter().map_while(|x| 16i32.checked_div(x));
1288 ///
1289 /// assert_eq!(iter.next(), Some(-16));
1290 /// assert_eq!(iter.next(), Some(4));
1291 /// assert_eq!(iter.next(), None);
1292 /// ```
1293 ///
1294 /// Here's the same example, but with [`take_while`] and [`map`]:
1295 ///
1296 /// [`take_while`]: Iterator::take_while
1297 /// [`map`]: Iterator::map
1298 ///
1299 /// ```
1300 /// let a = [-1i32, 4, 0, 1];
1301 ///
1302 /// let mut iter = a.into_iter()
1303 /// .map(|x| 16i32.checked_div(x))
1304 /// .take_while(|x| x.is_some())
1305 /// .map(|x| x.unwrap());
1306 ///
1307 /// assert_eq!(iter.next(), Some(-16));
1308 /// assert_eq!(iter.next(), Some(4));
1309 /// assert_eq!(iter.next(), None);
1310 /// ```
1311 ///
1312 /// Stopping after an initial [`None`]:
1313 ///
1314 /// ```
1315 /// let a = [0, 1, 2, -3, 4, 5, -6];
1316 ///
1317 /// let iter = a.into_iter().map_while(|x| u32::try_from(x).ok());
1318 /// let vec: Vec<_> = iter.collect();
1319 ///
1320 /// // We have more elements that could fit in u32 (such as 4, 5), but `map_while` returned `None` for `-3`
1321 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1322 /// assert_eq!(vec, [0, 1, 2]);
1323 /// ```
1324 ///
1325 /// Because `map_while()` needs to look at the value in order to see if it
1326 /// should be included or not, consuming iterators will see that it is
1327 /// removed:
1328 ///
1329 /// ```
1330 /// let a = [1, 2, -3, 4];
1331 /// let mut iter = a.into_iter();
1332 ///
1333 /// let result: Vec<u32> = iter.by_ref()
1334 /// .map_while(|n| u32::try_from(n).ok())
1335 /// .collect();
1336 ///
1337 /// assert_eq!(result, [1, 2]);
1338 ///
1339 /// let result: Vec<i32> = iter.collect();
1340 ///
1341 /// assert_eq!(result, [4]);
1342 /// ```
1343 ///
1344 /// The `-3` is no longer there, because it was consumed in order to see if
1345 /// the iteration should stop, but wasn't placed back into the iterator.
1346 ///
1347 /// Note that unlike [`take_while`] this iterator is **not** fused.
1348 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1349 /// If you need a fused iterator, use [`fuse`].
1350 ///
1351 /// [`fuse`]: Iterator::fuse
1352 #[inline]
1353 #[stable(feature = "iter_map_while", since = "1.57.0")]
1354 #[rustc_diagnostic_item = "iter_map_while"]
1355 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1356 where
1357 Self: Sized,
1358 P: FnMut(Self::Item) -> Option<B>,
1359 {
1360 MapWhile::new(self, predicate)
1361 }
1362
1363 /// Creates an iterator that skips the first `n` elements.
1364 ///
1365 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1366 /// iterator is reached (whichever happens first). After that, all the remaining
1367 /// elements are yielded. In particular, if the original iterator is too short,
1368 /// then the returned iterator is empty.
1369 ///
1370 /// Rather than overriding this method directly, instead override the `nth` method.
1371 ///
1372 /// # Examples
1373 ///
1374 /// ```
1375 /// let a = [1, 2, 3];
1376 ///
1377 /// let mut iter = a.into_iter().skip(2);
1378 ///
1379 /// assert_eq!(iter.next(), Some(3));
1380 /// assert_eq!(iter.next(), None);
1381 /// ```
1382 #[inline]
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 #[rustc_diagnostic_item = "iter_skip"]
1385 fn skip(self, n: usize) -> Skip<Self>
1386 where
1387 Self: Sized,
1388 {
1389 Skip::new(self, n)
1390 }
1391
1392 /// Creates an iterator that yields the first `n` elements, or fewer
1393 /// if the underlying iterator ends sooner.
1394 ///
1395 /// `take(n)` yields elements until `n` elements are yielded or the end of
1396 /// the iterator is reached (whichever happens first).
1397 /// The returned iterator is a prefix of length `n` if the original iterator
1398 /// contains at least `n` elements, otherwise it contains all of the
1399 /// (fewer than `n`) elements of the original iterator.
1400 ///
1401 /// # Examples
1402 ///
1403 /// Basic usage:
1404 ///
1405 /// ```
1406 /// let a = [1, 2, 3];
1407 ///
1408 /// let mut iter = a.into_iter().take(2);
1409 ///
1410 /// assert_eq!(iter.next(), Some(1));
1411 /// assert_eq!(iter.next(), Some(2));
1412 /// assert_eq!(iter.next(), None);
1413 /// ```
1414 ///
1415 /// `take()` is often used with an infinite iterator, to make it finite:
1416 ///
1417 /// ```
1418 /// let mut iter = (0..).take(3);
1419 ///
1420 /// assert_eq!(iter.next(), Some(0));
1421 /// assert_eq!(iter.next(), Some(1));
1422 /// assert_eq!(iter.next(), Some(2));
1423 /// assert_eq!(iter.next(), None);
1424 /// ```
1425 ///
1426 /// If less than `n` elements are available,
1427 /// `take` will limit itself to the size of the underlying iterator:
1428 ///
1429 /// ```
1430 /// let v = [1, 2];
1431 /// let mut iter = v.into_iter().take(5);
1432 /// assert_eq!(iter.next(), Some(1));
1433 /// assert_eq!(iter.next(), Some(2));
1434 /// assert_eq!(iter.next(), None);
1435 /// ```
1436 ///
1437 /// Use [`by_ref`] to take from the iterator without consuming it, and then
1438 /// continue using the original iterator:
1439 ///
1440 /// ```
1441 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1442 ///
1443 /// // Take the first two words.
1444 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1445 /// assert_eq!(hello_world, vec!["hello", "world"]);
1446 ///
1447 /// // Collect the rest of the words.
1448 /// // We can only do this because we used `by_ref` earlier.
1449 /// let of_rust: Vec<_> = words.collect();
1450 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1451 /// ```
1452 ///
1453 /// [`by_ref`]: Iterator::by_ref
1454 #[doc(alias = "limit")]
1455 #[inline]
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 #[rustc_diagnostic_item = "iter_take"]
1458 fn take(self, n: usize) -> Take<Self>
1459 where
1460 Self: Sized,
1461 {
1462 Take::new(self, n)
1463 }
1464
1465 /// An iterator adapter which, like [`fold`], holds internal state, but
1466 /// unlike [`fold`], produces a new iterator.
1467 ///
1468 /// [`fold`]: Iterator::fold
1469 ///
1470 /// `scan()` takes two arguments: an initial value which seeds the internal
1471 /// state, and a closure with two arguments, the first being a mutable
1472 /// reference to the internal state and the second an iterator element.
1473 /// The closure can assign to the internal state to share state between
1474 /// iterations.
1475 ///
1476 /// On iteration, the closure will be applied to each element of the
1477 /// iterator and the return value from the closure, an [`Option`], is
1478 /// returned by the `next` method. Thus the closure can return
1479 /// `Some(value)` to yield `value`, or `None` to end the iteration.
1480 ///
1481 /// # Examples
1482 ///
1483 /// ```
1484 /// let a = [1, 2, 3, 4];
1485 ///
1486 /// let mut iter = a.into_iter().scan(1, |state, x| {
1487 /// // each iteration, we'll multiply the state by the element ...
1488 /// *state = *state * x;
1489 ///
1490 /// // ... and terminate if the state exceeds 6
1491 /// if *state > 6 {
1492 /// return None;
1493 /// }
1494 /// // ... else yield the negation of the state
1495 /// Some(-*state)
1496 /// });
1497 ///
1498 /// assert_eq!(iter.next(), Some(-1));
1499 /// assert_eq!(iter.next(), Some(-2));
1500 /// assert_eq!(iter.next(), Some(-6));
1501 /// assert_eq!(iter.next(), None);
1502 /// ```
1503 #[inline]
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 #[rustc_diagnostic_item = "iter_scan"]
1506 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1507 where
1508 Self: Sized,
1509 F: FnMut(&mut St, Self::Item) -> Option<B>,
1510 {
1511 Scan::new(self, initial_state, f)
1512 }
1513
1514 /// Creates an iterator that works like map, but flattens nested structure.
1515 ///
1516 /// The [`map`] adapter is very useful, but only when the closure
1517 /// argument produces values. If it produces an iterator instead, there's
1518 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1519 /// on its own.
1520 ///
1521 /// You can think of `flat_map(f)` as the semantic equivalent
1522 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1523 ///
1524 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1525 /// one item for each element, and `flat_map()`'s closure returns an
1526 /// iterator for each element.
1527 ///
1528 /// [`map`]: Iterator::map
1529 /// [`flatten`]: Iterator::flatten
1530 ///
1531 /// # Examples
1532 ///
1533 /// ```
1534 /// let words = ["alpha", "beta", "gamma"];
1535 ///
1536 /// // chars() returns an iterator
1537 /// let merged: String = words.iter()
1538 /// .flat_map(|s| s.chars())
1539 /// .collect();
1540 /// assert_eq!(merged, "alphabetagamma");
1541 /// ```
1542 #[inline]
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 #[rustc_non_const_trait_method]
1545 #[rustc_diagnostic_item = "iter_flat_map"]
1546 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1547 where
1548 Self: Sized,
1549 U: IntoIterator,
1550 F: FnMut(Self::Item) -> U,
1551 {
1552 FlatMap::new(self, f)
1553 }
1554
1555 /// Creates an iterator that flattens nested structure.
1556 ///
1557 /// This is useful when you have an iterator of iterators or an iterator of
1558 /// things that can be turned into iterators and you want to remove one
1559 /// level of indirection.
1560 ///
1561 /// # Examples
1562 ///
1563 /// Basic usage:
1564 ///
1565 /// ```
1566 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1567 /// let flattened: Vec<_> = data.into_iter().flatten().collect();
1568 /// assert_eq!(flattened, [1, 2, 3, 4, 5, 6]);
1569 /// ```
1570 ///
1571 /// Mapping and then flattening:
1572 ///
1573 /// ```
1574 /// let words = ["alpha", "beta", "gamma"];
1575 ///
1576 /// // chars() returns an iterator
1577 /// let merged: String = words.iter()
1578 /// .map(|s| s.chars())
1579 /// .flatten()
1580 /// .collect();
1581 /// assert_eq!(merged, "alphabetagamma");
1582 /// ```
1583 ///
1584 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1585 /// in this case since it conveys intent more clearly:
1586 ///
1587 /// ```
1588 /// let words = ["alpha", "beta", "gamma"];
1589 ///
1590 /// // chars() returns an iterator
1591 /// let merged: String = words.iter()
1592 /// .flat_map(|s| s.chars())
1593 /// .collect();
1594 /// assert_eq!(merged, "alphabetagamma");
1595 /// ```
1596 ///
1597 /// Flattening works on any `IntoIterator` type, including `Option` and `Result`:
1598 ///
1599 /// ```
1600 /// let options = vec![Some(123), Some(321), None, Some(231)];
1601 /// let flattened_options: Vec<_> = options.into_iter().flatten().collect();
1602 /// assert_eq!(flattened_options, [123, 321, 231]);
1603 ///
1604 /// let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];
1605 /// let flattened_results: Vec<_> = results.into_iter().flatten().collect();
1606 /// assert_eq!(flattened_results, [123, 321, 231]);
1607 /// ```
1608 ///
1609 /// Flattening only removes one level of nesting at a time:
1610 ///
1611 /// ```
1612 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1613 ///
1614 /// let d2: Vec<_> = d3.into_iter().flatten().collect();
1615 /// assert_eq!(d2, [[1, 2], [3, 4], [5, 6], [7, 8]]);
1616 ///
1617 /// let d1: Vec<_> = d3.into_iter().flatten().flatten().collect();
1618 /// assert_eq!(d1, [1, 2, 3, 4, 5, 6, 7, 8]);
1619 /// ```
1620 ///
1621 /// Here we see that `flatten()` does not perform a "deep" flatten.
1622 /// Instead, only one level of nesting is removed. That is, if you
1623 /// `flatten()` a three-dimensional array, the result will be
1624 /// two-dimensional and not one-dimensional. To get a one-dimensional
1625 /// structure, you have to `flatten()` again.
1626 ///
1627 /// [`flat_map()`]: Iterator::flat_map
1628 #[inline]
1629 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1630 #[rustc_diagnostic_item = "iter_flatten"]
1631 fn flatten(self) -> Flatten<Self>
1632 where
1633 Self: Sized,
1634 Self::Item: IntoIterator,
1635 {
1636 Flatten::new(self)
1637 }
1638
1639 /// Calls the given function `f` for each contiguous window of size `N` over
1640 /// `self` and returns an iterator over the outputs of `f`. Like [`slice::windows()`],
1641 /// the windows during mapping overlap as well.
1642 ///
1643 /// In the following example, the closure is called three times with the
1644 /// arguments `&['a', 'b']`, `&['b', 'c']` and `&['c', 'd']` respectively.
1645 ///
1646 /// ```
1647 /// #![feature(iter_map_windows)]
1648 ///
1649 /// let strings = "abcd".chars()
1650 /// .map_windows(|[x, y]| format!("{}+{}", x, y))
1651 /// .collect::<Vec<String>>();
1652 ///
1653 /// assert_eq!(strings, vec!["a+b", "b+c", "c+d"]);
1654 /// ```
1655 ///
1656 /// Note that the const parameter `N` is usually inferred by the
1657 /// destructured argument in the closure.
1658 ///
1659 /// The returned iterator yields 𝑘 − `N` + 1 items (where 𝑘 is the number of
1660 /// items yielded by `self`). If 𝑘 is less than `N`, this method yields an
1661 /// empty iterator.
1662 ///
1663 /// [`slice::windows()`]: slice::windows
1664 /// [`FusedIterator`]: crate::iter::FusedIterator
1665 ///
1666 /// # Panics
1667 ///
1668 /// Panics if `N` is zero.
1669 ///
1670 /// # Examples
1671 ///
1672 /// Building the sums of neighboring numbers.
1673 ///
1674 /// ```
1675 /// #![feature(iter_map_windows)]
1676 ///
1677 /// let mut it = [1, 3, 8, 1].iter().map_windows(|&[a, b]| a + b);
1678 /// assert_eq!(it.next(), Some(4)); // 1 + 3
1679 /// assert_eq!(it.next(), Some(11)); // 3 + 8
1680 /// assert_eq!(it.next(), Some(9)); // 8 + 1
1681 /// assert_eq!(it.next(), None);
1682 /// ```
1683 ///
1684 /// Since the elements in the following example implement `Copy`, we can
1685 /// just copy the array and get an iterator over the windows.
1686 ///
1687 /// ```
1688 /// #![feature(iter_map_windows)]
1689 ///
1690 /// let mut it = "ferris".chars().map_windows(|w: &[_; 3]| *w);
1691 /// assert_eq!(it.next(), Some(['f', 'e', 'r']));
1692 /// assert_eq!(it.next(), Some(['e', 'r', 'r']));
1693 /// assert_eq!(it.next(), Some(['r', 'r', 'i']));
1694 /// assert_eq!(it.next(), Some(['r', 'i', 's']));
1695 /// assert_eq!(it.next(), None);
1696 /// ```
1697 ///
1698 /// You can also use this function to check the sortedness of an iterator.
1699 /// For the simple case, rather use [`Iterator::is_sorted`].
1700 ///
1701 /// ```
1702 /// #![feature(iter_map_windows)]
1703 ///
1704 /// let mut it = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].iter()
1705 /// .map_windows(|[a, b]| a <= b);
1706 ///
1707 /// assert_eq!(it.next(), Some(true)); // 0.5 <= 1.0
1708 /// assert_eq!(it.next(), Some(true)); // 1.0 <= 3.5
1709 /// assert_eq!(it.next(), Some(false)); // 3.5 <= 3.0
1710 /// assert_eq!(it.next(), Some(true)); // 3.0 <= 8.5
1711 /// assert_eq!(it.next(), Some(true)); // 8.5 <= 8.5
1712 /// assert_eq!(it.next(), Some(false)); // 8.5 <= NAN
1713 /// assert_eq!(it.next(), None);
1714 /// ```
1715 ///
1716 /// For non-fused iterators, the window is reset after `None` is yielded.
1717 ///
1718 /// ```
1719 /// #![feature(iter_map_windows)]
1720 ///
1721 /// #[derive(Default)]
1722 /// struct NonFusedIterator {
1723 /// state: i32,
1724 /// }
1725 ///
1726 /// impl Iterator for NonFusedIterator {
1727 /// type Item = i32;
1728 ///
1729 /// fn next(&mut self) -> Option<i32> {
1730 /// let val = self.state;
1731 /// self.state = self.state + 1;
1732 ///
1733 /// // Skip every 5th number
1734 /// if (val + 1) % 5 == 0 {
1735 /// None
1736 /// } else {
1737 /// Some(val)
1738 /// }
1739 /// }
1740 /// }
1741 ///
1742 ///
1743 /// let mut iter = NonFusedIterator::default();
1744 ///
1745 /// assert_eq!(iter.next(), Some(0));
1746 /// assert_eq!(iter.next(), Some(1));
1747 /// assert_eq!(iter.next(), Some(2));
1748 /// assert_eq!(iter.next(), Some(3));
1749 /// assert_eq!(iter.next(), None);
1750 /// assert_eq!(iter.next(), Some(5));
1751 /// assert_eq!(iter.next(), Some(6));
1752 /// assert_eq!(iter.next(), Some(7));
1753 /// assert_eq!(iter.next(), Some(8));
1754 /// assert_eq!(iter.next(), None);
1755 /// assert_eq!(iter.next(), Some(10));
1756 /// assert_eq!(iter.next(), Some(11));
1757 ///
1758 /// let mut iter = NonFusedIterator::default()
1759 /// .map_windows(|arr: &[_; 2]| *arr);
1760 ///
1761 /// assert_eq!(iter.next(), Some([0, 1]));
1762 /// assert_eq!(iter.next(), Some([1, 2]));
1763 /// assert_eq!(iter.next(), Some([2, 3]));
1764 /// assert_eq!(iter.next(), None);
1765 ///
1766 /// assert_eq!(iter.next(), Some([5, 6]));
1767 /// assert_eq!(iter.next(), Some([6, 7]));
1768 /// assert_eq!(iter.next(), Some([7, 8]));
1769 /// assert_eq!(iter.next(), None);
1770 ///
1771 /// assert_eq!(iter.next(), Some([10, 11]));
1772 /// assert_eq!(iter.next(), Some([11, 12]));
1773 /// assert_eq!(iter.next(), Some([12, 13]));
1774 /// assert_eq!(iter.next(), None);
1775 /// ```
1776 #[inline]
1777 #[unstable(feature = "iter_map_windows", issue = "87155")]
1778 fn map_windows<F, R, #[lint::panics_when_zero] const N: usize>(
1779 self,
1780 f: F,
1781 ) -> MapWindows<Self, F, N>
1782 where
1783 Self: Sized,
1784 F: FnMut(&[Self::Item; N]) -> R,
1785 {
1786 MapWindows::new(self, f)
1787 }
1788
1789 /// Creates an iterator which ends after the first [`None`].
1790 ///
1791 /// After an iterator returns [`None`], future calls may or may not yield
1792 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1793 /// [`None`] is given, it will always return [`None`] forever.
1794 ///
1795 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1796 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1797 /// if the [`FusedIterator`] trait is improperly implemented.
1798 ///
1799 /// [`Some(T)`]: Some
1800 /// [`FusedIterator`]: crate::iter::FusedIterator
1801 ///
1802 /// # Examples
1803 ///
1804 /// ```
1805 /// // an iterator which alternates between Some and None
1806 /// struct Alternate {
1807 /// state: i32,
1808 /// }
1809 ///
1810 /// impl Iterator for Alternate {
1811 /// type Item = i32;
1812 ///
1813 /// fn next(&mut self) -> Option<i32> {
1814 /// let val = self.state;
1815 /// self.state = self.state + 1;
1816 ///
1817 /// // if it's even, Some(i32), else None
1818 /// (val % 2 == 0).then_some(val)
1819 /// }
1820 /// }
1821 ///
1822 /// let mut iter = Alternate { state: 0 };
1823 ///
1824 /// // we can see our iterator going back and forth
1825 /// assert_eq!(iter.next(), Some(0));
1826 /// assert_eq!(iter.next(), None);
1827 /// assert_eq!(iter.next(), Some(2));
1828 /// assert_eq!(iter.next(), None);
1829 ///
1830 /// // however, once we fuse it...
1831 /// let mut iter = iter.fuse();
1832 ///
1833 /// assert_eq!(iter.next(), Some(4));
1834 /// assert_eq!(iter.next(), None);
1835 ///
1836 /// // it will always return `None` after the first time.
1837 /// assert_eq!(iter.next(), None);
1838 /// assert_eq!(iter.next(), None);
1839 /// assert_eq!(iter.next(), None);
1840 /// ```
1841 #[inline]
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 #[rustc_diagnostic_item = "iter_fuse"]
1844 fn fuse(self) -> Fuse<Self>
1845 where
1846 Self: Sized,
1847 {
1848 Fuse::new(self)
1849 }
1850
1851 /// Does something with each element of an iterator, passing the value on.
1852 ///
1853 /// When using iterators, you'll often chain several of them together.
1854 /// While working on such code, you might want to check out what's
1855 /// happening at various parts in the pipeline. To do that, insert
1856 /// a call to `inspect()`.
1857 ///
1858 /// It's more common for `inspect()` to be used as a debugging tool than to
1859 /// exist in your final code, but applications may find it useful in certain
1860 /// situations when errors need to be logged before being discarded.
1861 ///
1862 /// # Examples
1863 ///
1864 /// Basic usage:
1865 ///
1866 /// ```
1867 /// let a = [1, 4, 2, 3];
1868 ///
1869 /// // this iterator sequence is complex.
1870 /// let sum = a.iter()
1871 /// .cloned()
1872 /// .filter(|x| x % 2 == 0)
1873 /// .fold(0, |sum, i| sum + i);
1874 ///
1875 /// println!("{sum}");
1876 ///
1877 /// // let's add some inspect() calls to investigate what's happening
1878 /// let sum = a.iter()
1879 /// .cloned()
1880 /// .inspect(|x| println!("about to filter: {x}"))
1881 /// .filter(|x| x % 2 == 0)
1882 /// .inspect(|x| println!("made it through filter: {x}"))
1883 /// .fold(0, |sum, i| sum + i);
1884 ///
1885 /// println!("{sum}");
1886 /// ```
1887 ///
1888 /// This will print:
1889 ///
1890 /// ```text
1891 /// 6
1892 /// about to filter: 1
1893 /// about to filter: 4
1894 /// made it through filter: 4
1895 /// about to filter: 2
1896 /// made it through filter: 2
1897 /// about to filter: 3
1898 /// 6
1899 /// ```
1900 ///
1901 /// Logging errors before discarding them:
1902 ///
1903 /// ```
1904 /// let lines = ["1", "2", "a"];
1905 ///
1906 /// let sum: i32 = lines
1907 /// .iter()
1908 /// .map(|line| line.parse::<i32>())
1909 /// .inspect(|num| {
1910 /// if let Err(ref e) = *num {
1911 /// println!("Parsing error: {e}");
1912 /// }
1913 /// })
1914 /// .filter_map(Result::ok)
1915 /// .sum();
1916 ///
1917 /// println!("Sum: {sum}");
1918 /// ```
1919 ///
1920 /// This will print:
1921 ///
1922 /// ```text
1923 /// Parsing error: invalid digit found in string
1924 /// Sum: 3
1925 /// ```
1926 #[inline]
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 #[rustc_diagnostic_item = "inspect"]
1929 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1930 where
1931 Self: Sized,
1932 F: FnMut(&Self::Item),
1933 {
1934 Inspect::new(self, f)
1935 }
1936
1937 /// Creates a "by reference" adapter for this instance of `Iterator`.
1938 ///
1939 /// Consuming method calls (direct or indirect calls to `next`)
1940 /// on the "by reference" adapter will consume the original iterator,
1941 /// but ownership-taking methods (those with a `self` parameter)
1942 /// only take ownership of the "by reference" iterator.
1943 ///
1944 /// This is useful for applying ownership-taking methods
1945 /// (such as `take` in the example below)
1946 /// without giving up ownership of the original iterator,
1947 /// so you can use the original iterator afterwards.
1948 ///
1949 /// Uses [`impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; ...}`](Iterator#impl-Iterator-for-%26mut+I).
1950 ///
1951 /// # Examples
1952 ///
1953 /// ```
1954 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1955 ///
1956 /// // Take the first two words.
1957 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1958 /// assert_eq!(hello_world, vec!["hello", "world"]);
1959 ///
1960 /// // Collect the rest of the words.
1961 /// // We can only do this because we used `by_ref` earlier.
1962 /// let of_rust: Vec<_> = words.collect();
1963 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1964 /// ```
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 fn by_ref(&mut self) -> &mut Self
1967 where
1968 Self: Sized,
1969 {
1970 self
1971 }
1972
1973 /// Transforms an iterator into a collection.
1974 ///
1975 /// `collect()` takes ownership of an iterator and produces whichever
1976 /// collection type you request. The iterator itself carries no knowledge of
1977 /// the eventual container; the target collection is chosen entirely by the
1978 /// type you ask `collect()` to return. This makes `collect()` one of the
1979 /// more powerful methods in the standard library, and it shows up in a wide
1980 /// variety of contexts.
1981 ///
1982 /// The most basic pattern in which `collect()` is used is to turn one
1983 /// collection into another. You take a collection, call [`iter`] on it,
1984 /// do a bunch of transformations, and then `collect()` at the end.
1985 ///
1986 /// `collect()` can also create instances of types that are not typical
1987 /// collections. For example, a [`String`] can be built from [`char`]s,
1988 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1989 /// into `Result<Collection<T>, E>`. See the examples below for more.
1990 ///
1991 /// Because `collect()` is so general, it can cause problems with type
1992 /// inference. As such, `collect()` is one of the few times you'll see
1993 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1994 /// helps the inference algorithm understand specifically which collection
1995 /// you're trying to collect into.
1996 ///
1997 /// # Examples
1998 ///
1999 /// Basic usage:
2000 ///
2001 /// ```
2002 /// let a = [1, 2, 3];
2003 ///
2004 /// let doubled: Vec<i32> = a.iter()
2005 /// .map(|x| x * 2)
2006 /// .collect();
2007 ///
2008 /// assert_eq!(vec![2, 4, 6], doubled);
2009 /// ```
2010 ///
2011 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
2012 /// we could collect into, for example, a [`VecDeque<T>`] instead:
2013 ///
2014 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
2015 ///
2016 /// ```
2017 /// use std::collections::VecDeque;
2018 ///
2019 /// let a = [1, 2, 3];
2020 ///
2021 /// let doubled: VecDeque<i32> = a.iter().map(|x| x * 2).collect();
2022 ///
2023 /// assert_eq!(2, doubled[0]);
2024 /// assert_eq!(4, doubled[1]);
2025 /// assert_eq!(6, doubled[2]);
2026 /// ```
2027 ///
2028 /// Using the 'turbofish' instead of annotating `doubled`:
2029 ///
2030 /// ```
2031 /// let a = [1, 2, 3];
2032 ///
2033 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
2034 ///
2035 /// assert_eq!(vec![2, 4, 6], doubled);
2036 /// ```
2037 ///
2038 /// Because `collect()` only cares about what you're collecting into, you can
2039 /// still use a partial type hint, `_`, with the turbofish:
2040 ///
2041 /// ```
2042 /// let a = [1, 2, 3];
2043 ///
2044 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
2045 ///
2046 /// assert_eq!(vec![2, 4, 6], doubled);
2047 /// ```
2048 ///
2049 /// Using `collect()` to make a [`String`]:
2050 ///
2051 /// ```
2052 /// let chars = ['g', 'd', 'k', 'k', 'n'];
2053 ///
2054 /// let hello: String = chars.into_iter()
2055 /// .map(|x| x as u8)
2056 /// .map(|x| (x + 1) as char)
2057 /// .collect();
2058 ///
2059 /// assert_eq!("hello", hello);
2060 /// ```
2061 ///
2062 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
2063 /// see if any of them failed:
2064 ///
2065 /// ```
2066 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
2067 ///
2068 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2069 ///
2070 /// // gives us the first error
2071 /// assert_eq!(Err("nope"), result);
2072 ///
2073 /// let results = [Ok(1), Ok(3)];
2074 ///
2075 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2076 ///
2077 /// // gives us the list of answers
2078 /// assert_eq!(Ok(vec![1, 3]), result);
2079 /// ```
2080 ///
2081 /// [`iter`]: Iterator::next
2082 /// [`String`]: ../../std/string/struct.String.html
2083 /// [`char`]: type@char
2084 #[inline]
2085 #[stable(feature = "rust1", since = "1.0.0")]
2086 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
2087 #[rustc_diagnostic_item = "iterator_collect_fn"]
2088 #[rustc_non_const_trait_method]
2089 fn collect<B: FromIterator<Self::Item>>(self) -> B
2090 where
2091 Self: Sized,
2092 {
2093 // This is too aggressive to turn on for everything all the time, but PR#137908
2094 // accidentally noticed that some rustc iterators had malformed `size_hint`s,
2095 // so this will help catch such things in debug-assertions-std runners,
2096 // even if users won't actually ever see it.
2097 if cfg!(debug_assertions) {
2098 let hint = self.size_hint();
2099 assert!(hint.1.is_none_or(|high| high >= hint.0), "Malformed size_hint {hint:?}");
2100 }
2101
2102 FromIterator::from_iter(self)
2103 }
2104
2105 /// Fallibly transforms an iterator into a collection, short circuiting if
2106 /// a failure is encountered.
2107 ///
2108 /// `try_collect()` is a variation of [`collect()`][`collect`] that allows fallible
2109 /// conversions during collection. Its main use case is simplifying conversions from
2110 /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
2111 /// types (e.g. [`Result`]).
2112 ///
2113 /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromIterator`];
2114 /// only the inner type produced on `Try::Output` must implement it. Concretely,
2115 /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
2116 /// [`FromIterator`], even though [`ControlFlow`] doesn't.
2117 ///
2118 /// Also, if a failure is encountered during `try_collect()`, the iterator is still valid and
2119 /// may continue to be used, in which case it will continue iterating starting after the element that
2120 /// triggered the failure. See the last example below for an example of how this works.
2121 ///
2122 /// # Examples
2123 /// Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:
2124 /// ```
2125 /// #![feature(iterator_try_collect)]
2126 ///
2127 /// let u = vec![Some(1), Some(2), Some(3)];
2128 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2129 /// assert_eq!(v, Some(vec![1, 2, 3]));
2130 /// ```
2131 ///
2132 /// Failing to collect in the same way:
2133 /// ```
2134 /// #![feature(iterator_try_collect)]
2135 ///
2136 /// let u = vec![Some(1), Some(2), None, Some(3)];
2137 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2138 /// assert_eq!(v, None);
2139 /// ```
2140 ///
2141 /// A similar example, but with `Result`:
2142 /// ```
2143 /// #![feature(iterator_try_collect)]
2144 ///
2145 /// let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];
2146 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2147 /// assert_eq!(v, Ok(vec![1, 2, 3]));
2148 ///
2149 /// let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];
2150 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2151 /// assert_eq!(v, Err(()));
2152 /// ```
2153 ///
2154 /// Finally, even [`ControlFlow`] works, despite the fact that it
2155 /// doesn't implement [`FromIterator`]. Note also that the iterator can
2156 /// continue to be used, even if a failure is encountered:
2157 ///
2158 /// ```
2159 /// #![feature(iterator_try_collect)]
2160 ///
2161 /// use core::ops::ControlFlow::{Break, Continue};
2162 ///
2163 /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
2164 /// let mut it = u.into_iter();
2165 ///
2166 /// let v = it.try_collect::<Vec<_>>();
2167 /// assert_eq!(v, Break(3));
2168 ///
2169 /// let v = it.try_collect::<Vec<_>>();
2170 /// assert_eq!(v, Continue(vec![4, 5]));
2171 /// ```
2172 ///
2173 /// [`collect`]: Iterator::collect
2174 #[inline]
2175 #[unstable(feature = "iterator_try_collect", issue = "94047")]
2176 #[rustc_non_const_trait_method]
2177 fn try_collect<B>(&mut self) -> ChangeOutputType<Self::Item, B>
2178 where
2179 Self: Sized,
2180 Self::Item: Try<Residual: Residual<B>>,
2181 B: FromIterator<<Self::Item as Try>::Output>,
2182 {
2183 try_process(ByRefSized(self), |i| i.collect())
2184 }
2185
2186 /// Collects all the items from an iterator into a collection.
2187 ///
2188 /// This method consumes the iterator and adds all its items to the
2189 /// passed collection. The collection is then returned, so the call chain
2190 /// can be continued.
2191 ///
2192 /// This is useful when you already have a collection and want to add
2193 /// the iterator items to it.
2194 ///
2195 /// This method is a convenience method to call [Extend::extend](trait.Extend.html),
2196 /// but instead of being called on a collection, it's called on an iterator.
2197 ///
2198 /// # Examples
2199 ///
2200 /// Basic usage:
2201 ///
2202 /// ```
2203 /// #![feature(iter_collect_into)]
2204 ///
2205 /// let a = [1, 2, 3];
2206 /// let mut vec: Vec::<i32> = vec![0, 1];
2207 ///
2208 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2209 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2210 ///
2211 /// assert_eq!(vec, vec![0, 1, 2, 4, 6, 10, 20, 30]);
2212 /// ```
2213 ///
2214 /// `Vec` can have a manual set capacity to avoid reallocating it:
2215 ///
2216 /// ```
2217 /// #![feature(iter_collect_into)]
2218 ///
2219 /// let a = [1, 2, 3];
2220 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2221 ///
2222 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2223 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2224 ///
2225 /// assert_eq!(6, vec.capacity());
2226 /// assert_eq!(vec, vec![2, 4, 6, 10, 20, 30]);
2227 /// ```
2228 ///
2229 /// The returned mutable reference can be used to continue the call chain:
2230 ///
2231 /// ```
2232 /// #![feature(iter_collect_into)]
2233 ///
2234 /// let a = [1, 2, 3];
2235 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2236 ///
2237 /// let count = a.iter().collect_into(&mut vec).iter().count();
2238 ///
2239 /// assert_eq!(count, vec.len());
2240 /// assert_eq!(vec, vec![1, 2, 3]);
2241 ///
2242 /// let count = a.iter().collect_into(&mut vec).iter().count();
2243 ///
2244 /// assert_eq!(count, vec.len());
2245 /// assert_eq!(vec, vec![1, 2, 3, 1, 2, 3]);
2246 /// ```
2247 #[inline]
2248 #[unstable(feature = "iter_collect_into", issue = "94780")]
2249 #[rustc_non_const_trait_method]
2250 fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
2251 where
2252 Self: Sized,
2253 {
2254 collection.extend(self);
2255 collection
2256 }
2257
2258 /// Consumes an iterator, creating two collections from it.
2259 ///
2260 /// The predicate passed to `partition()` can return `true`, or `false`.
2261 /// `partition()` returns a pair, all of the elements for which it returned
2262 /// `true`, and all of the elements for which it returned `false`.
2263 ///
2264 /// See also [`is_partitioned()`] and [`partition_in_place()`].
2265 ///
2266 /// [`is_partitioned()`]: Iterator::is_partitioned
2267 /// [`partition_in_place()`]: Iterator::partition_in_place
2268 ///
2269 /// # Examples
2270 ///
2271 /// ```
2272 /// let a = [1, 2, 3];
2273 ///
2274 /// let (even, odd): (Vec<_>, Vec<_>) = a
2275 /// .into_iter()
2276 /// .partition(|n| n % 2 == 0);
2277 ///
2278 /// assert_eq!(even, [2]);
2279 /// assert_eq!(odd, [1, 3]);
2280 /// ```
2281 #[stable(feature = "rust1", since = "1.0.0")]
2282 #[rustc_non_const_trait_method]
2283 #[rustc_diagnostic_item = "iter_partition"]
2284 fn partition<B, F>(self, f: F) -> (B, B)
2285 where
2286 Self: Sized,
2287 B: Default + Extend<Self::Item>,
2288 F: FnMut(&Self::Item) -> bool,
2289 {
2290 #[inline]
2291 fn extend<'a, T, B: Extend<T>>(
2292 mut f: impl FnMut(&T) -> bool + 'a,
2293 left: &'a mut B,
2294 right: &'a mut B,
2295 ) -> impl FnMut((), T) + 'a {
2296 move |(), x| {
2297 if f(&x) {
2298 left.extend_one(x);
2299 } else {
2300 right.extend_one(x);
2301 }
2302 }
2303 }
2304
2305 let mut left: B = Default::default();
2306 let mut right: B = Default::default();
2307
2308 self.fold((), extend(f, &mut left, &mut right));
2309
2310 (left, right)
2311 }
2312
2313 /// Reorders the elements of this iterator *in-place* according to the given predicate,
2314 /// such that all those that return `true` precede all those that return `false`.
2315 /// Returns the number of `true` elements found.
2316 ///
2317 /// The relative order of partitioned items is not maintained.
2318 ///
2319 /// # Current implementation
2320 ///
2321 /// The current algorithm tries to find the first element for which the predicate evaluates
2322 /// to false and the last element for which it evaluates to true, and repeatedly swaps them.
2323 ///
2324 /// Time complexity: *O*(*n*)
2325 ///
2326 /// See also [`is_partitioned()`] and [`partition()`].
2327 ///
2328 /// [`is_partitioned()`]: Iterator::is_partitioned
2329 /// [`partition()`]: Iterator::partition
2330 ///
2331 /// # Examples
2332 ///
2333 /// ```
2334 /// #![feature(iter_partition_in_place)]
2335 ///
2336 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
2337 ///
2338 /// // Partition in-place between evens and odds
2339 /// let i = a.iter_mut().partition_in_place(|n| n % 2 == 0);
2340 ///
2341 /// assert_eq!(i, 3);
2342 /// assert!(a[..i].iter().all(|n| n % 2 == 0)); // evens
2343 /// assert!(a[i..].iter().all(|n| n % 2 == 1)); // odds
2344 /// ```
2345 #[unstable(feature = "iter_partition_in_place", issue = "62543")]
2346 #[rustc_non_const_trait_method]
2347 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
2348 where
2349 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
2350 P: FnMut(&T) -> bool,
2351 {
2352 // FIXME: should we worry about the count overflowing? The only way to have more than
2353 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
2354
2355 // These closure "factory" functions exist to avoid genericity in `Self`.
2356
2357 #[inline]
2358 fn is_false<'a, T>(
2359 predicate: &'a mut impl FnMut(&T) -> bool,
2360 true_count: &'a mut usize,
2361 ) -> impl FnMut(&&mut T) -> bool + 'a {
2362 move |x| {
2363 let p = predicate(&**x);
2364 *true_count += p as usize;
2365 !p
2366 }
2367 }
2368
2369 #[inline]
2370 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
2371 move |x| predicate(&**x)
2372 }
2373
2374 // Repeatedly find the first `false` and swap it with the last `true`.
2375 let mut true_count = 0;
2376 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
2377 if let Some(tail) = self.rfind(is_true(predicate)) {
2378 crate::mem::swap(head, tail);
2379 true_count += 1;
2380 } else {
2381 break;
2382 }
2383 }
2384 true_count
2385 }
2386
2387 /// Checks if the elements of this iterator are partitioned according to the given predicate,
2388 /// such that all those that return `true` precede all those that return `false`.
2389 ///
2390 /// See also [`partition()`] and [`partition_in_place()`].
2391 ///
2392 /// [`partition()`]: Iterator::partition
2393 /// [`partition_in_place()`]: Iterator::partition_in_place
2394 ///
2395 /// # Examples
2396 ///
2397 /// ```
2398 /// #![feature(iter_is_partitioned)]
2399 ///
2400 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
2401 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
2402 /// ```
2403 #[unstable(feature = "iter_is_partitioned", issue = "62544")]
2404 #[rustc_non_const_trait_method]
2405 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
2406 where
2407 Self: Sized,
2408 P: FnMut(Self::Item) -> bool,
2409 {
2410 // Either all items test `true`, or the first clause stops at `false`
2411 // and we check that there are no more `true` items after that.
2412 self.all(&mut predicate) || !self.any(predicate)
2413 }
2414
2415 /// An iterator method that applies a function as long as it returns
2416 /// successfully, producing a single, final value.
2417 ///
2418 /// `try_fold()` takes two arguments: an initial value, and a closure with
2419 /// two arguments: an 'accumulator', and an element. The closure either
2420 /// returns successfully, with the value that the accumulator should have
2421 /// for the next iteration, or it returns failure, with an error value that
2422 /// is propagated back to the caller immediately (short-circuiting).
2423 ///
2424 /// The initial value is the value the accumulator will have on the first
2425 /// call. If applying the closure succeeded against every element of the
2426 /// iterator, `try_fold()` returns the final accumulator as success.
2427 ///
2428 /// Folding is useful whenever you have a collection of something, and want
2429 /// to produce a single value from it.
2430 ///
2431 /// # Note to Implementors
2432 ///
2433 /// Several of the other (forward) methods have default implementations in
2434 /// terms of this one, so try to implement this explicitly if it can
2435 /// do something better than the default `for` loop implementation.
2436 ///
2437 /// In particular, try to have this call `try_fold()` on the internal parts
2438 /// from which this iterator is composed. If multiple calls are needed,
2439 /// the `?` operator may be convenient for chaining the accumulator value
2440 /// along, but beware any invariants that need to be upheld before those
2441 /// early returns. This is a `&mut self` method, so iteration needs to be
2442 /// resumable after hitting an error here.
2443 ///
2444 /// # Examples
2445 ///
2446 /// Basic usage:
2447 ///
2448 /// ```
2449 /// let a = [1, 2, 3];
2450 ///
2451 /// // the checked sum of all of the elements of the array
2452 /// let sum = a.into_iter().try_fold(0i8, |acc, x| acc.checked_add(x));
2453 ///
2454 /// assert_eq!(sum, Some(6));
2455 /// ```
2456 ///
2457 /// Short-circuiting:
2458 ///
2459 /// ```
2460 /// let a = [10, 20, 30, 100, 40, 50];
2461 /// let mut iter = a.into_iter();
2462 ///
2463 /// // This sum overflows when adding the 100 element
2464 /// let sum = iter.try_fold(0i8, |acc, x| acc.checked_add(x));
2465 /// assert_eq!(sum, None);
2466 ///
2467 /// // Because it short-circuited, the remaining elements are still
2468 /// // available through the iterator.
2469 /// assert_eq!(iter.len(), 2);
2470 /// assert_eq!(iter.next(), Some(40));
2471 /// ```
2472 ///
2473 /// While you cannot `break` from a closure, the [`ControlFlow`] type allows
2474 /// a similar idea:
2475 ///
2476 /// ```
2477 /// use std::ops::ControlFlow;
2478 ///
2479 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
2480 /// if let Some(next) = prev.checked_add(x) {
2481 /// ControlFlow::Continue(next)
2482 /// } else {
2483 /// ControlFlow::Break(prev)
2484 /// }
2485 /// });
2486 /// assert_eq!(triangular, ControlFlow::Break(120));
2487 ///
2488 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
2489 /// if let Some(next) = prev.checked_add(x) {
2490 /// ControlFlow::Continue(next)
2491 /// } else {
2492 /// ControlFlow::Break(prev)
2493 /// }
2494 /// });
2495 /// assert_eq!(triangular, ControlFlow::Continue(435));
2496 /// ```
2497 #[inline]
2498 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2499 #[rustc_diagnostic_item = "iter_try_fold"]
2500 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2501 where
2502 Self: Sized,
2503 F: [const] FnMut(B, Self::Item) -> R + [const] Destruct,
2504 R: [const] Try<Output = B>,
2505 {
2506 let mut accum = init;
2507 while let Some(x) = self.next() {
2508 accum = f(accum, x)?;
2509 }
2510 try { accum }
2511 }
2512
2513 /// An iterator method that applies a fallible function to each item in the
2514 /// iterator, stopping at the first error and returning that error.
2515 ///
2516 /// This can also be thought of as the fallible form of [`for_each()`]
2517 /// or as the stateless version of [`try_fold()`].
2518 ///
2519 /// [`for_each()`]: Iterator::for_each
2520 /// [`try_fold()`]: Iterator::try_fold
2521 ///
2522 /// # Examples
2523 ///
2524 /// ```
2525 /// use std::fs::rename;
2526 /// use std::io::{stdout, Write};
2527 /// use std::path::Path;
2528 ///
2529 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2530 ///
2531 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
2532 /// assert!(res.is_ok());
2533 ///
2534 /// let mut it = data.iter().cloned();
2535 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2536 /// assert!(res.is_err());
2537 /// // It short-circuited, so the remaining items are still in the iterator:
2538 /// assert_eq!(it.next(), Some("stale_bread.json"));
2539 /// ```
2540 ///
2541 /// The [`ControlFlow`] type can be used with this method for the situations
2542 /// in which you'd use `break` and `continue` in a normal loop:
2543 ///
2544 /// ```
2545 /// use std::ops::ControlFlow;
2546 ///
2547 /// let r = (2..100).try_for_each(|x| {
2548 /// if 323 % x == 0 {
2549 /// return ControlFlow::Break(x)
2550 /// }
2551 ///
2552 /// ControlFlow::Continue(())
2553 /// });
2554 /// assert_eq!(r, ControlFlow::Break(17));
2555 /// ```
2556 #[inline]
2557 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2558 #[rustc_non_const_trait_method]
2559 #[rustc_diagnostic_item = "iter_try_for_each"]
2560 fn try_for_each<F, R>(&mut self, f: F) -> R
2561 where
2562 Self: Sized,
2563 F: FnMut(Self::Item) -> R,
2564 R: Try<Output = ()>,
2565 {
2566 #[inline]
2567 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2568 move |(), x| f(x)
2569 }
2570
2571 self.try_fold((), call(f))
2572 }
2573
2574 /// Folds every element into an accumulator by applying an operation,
2575 /// returning the final result.
2576 ///
2577 /// `fold()` takes two arguments: an initial value, and a closure with two
2578 /// arguments: an 'accumulator', and an element. The closure returns the value that
2579 /// the accumulator should have for the next iteration.
2580 ///
2581 /// The initial value is the value the accumulator will have on the first
2582 /// call.
2583 ///
2584 /// After applying this closure to every element of the iterator, `fold()`
2585 /// returns the accumulator.
2586 ///
2587 /// This operation is sometimes called 'reduce' or 'inject'.
2588 ///
2589 /// Folding is useful whenever you have a collection of something, and want
2590 /// to produce a single value from it.
2591 ///
2592 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2593 /// might not terminate for infinite iterators, even on traits for which a
2594 /// result is determinable in finite time.
2595 ///
2596 /// Note: [`reduce()`] can be used to use the first element as the initial
2597 /// value, if the accumulator type and item type is the same.
2598 ///
2599 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2600 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2601 /// operators like `-` the order will affect the final result.
2602 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2603 ///
2604 /// # Note to Implementors
2605 ///
2606 /// Several of the other (forward) methods have default implementations in
2607 /// terms of this one, so try to implement this explicitly if it can
2608 /// do something better than the default `for` loop implementation.
2609 ///
2610 /// In particular, try to have this call `fold()` on the internal parts
2611 /// from which this iterator is composed.
2612 ///
2613 /// # Examples
2614 ///
2615 /// Basic usage:
2616 ///
2617 /// ```
2618 /// let a = [1, 2, 3];
2619 ///
2620 /// // the sum of all of the elements of the array
2621 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2622 ///
2623 /// assert_eq!(sum, 6);
2624 /// ```
2625 ///
2626 /// Let's walk through each step of the iteration here:
2627 ///
2628 /// | element | acc | x | result |
2629 /// |---------|-----|---|--------|
2630 /// | | 0 | | |
2631 /// | 1 | 0 | 1 | 1 |
2632 /// | 2 | 1 | 2 | 3 |
2633 /// | 3 | 3 | 3 | 6 |
2634 ///
2635 /// And so, our final result, `6`.
2636 ///
2637 /// This example demonstrates the left-associative nature of `fold()`:
2638 /// it builds a string, starting with an initial value
2639 /// and continuing with each element from the front until the back:
2640 ///
2641 /// ```
2642 /// let numbers = [1, 2, 3, 4, 5];
2643 ///
2644 /// let zero = "0".to_string();
2645 ///
2646 /// let result = numbers.iter().fold(zero, |acc, &x| {
2647 /// format!("({acc} + {x})")
2648 /// });
2649 ///
2650 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2651 /// ```
2652 /// It's common for people who haven't used iterators a lot to
2653 /// use a `for` loop with a list of things to build up a result. Those
2654 /// can be turned into `fold()`s:
2655 ///
2656 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2657 ///
2658 /// ```
2659 /// let numbers = [1, 2, 3, 4, 5];
2660 ///
2661 /// let mut result = 0;
2662 ///
2663 /// // for loop:
2664 /// for i in &numbers {
2665 /// result = result + i;
2666 /// }
2667 ///
2668 /// // fold:
2669 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2670 ///
2671 /// // they're the same
2672 /// assert_eq!(result, result2);
2673 /// ```
2674 ///
2675 /// [`reduce()`]: Iterator::reduce
2676 #[doc(alias = "inject", alias = "foldl")]
2677 #[inline]
2678 #[stable(feature = "rust1", since = "1.0.0")]
2679 #[rustc_diagnostic_item = "iter_fold"]
2680 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2681 where
2682 Self: Sized + [const] Destruct,
2683 F: [const] FnMut(B, Self::Item) -> B + [const] Destruct,
2684 {
2685 let mut accum = init;
2686 while let Some(x) = self.next() {
2687 accum = f(accum, x);
2688 }
2689 accum
2690 }
2691
2692 /// Reduces the elements to a single one, by repeatedly applying a reducing
2693 /// operation.
2694 ///
2695 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2696 /// result of the reduction.
2697 ///
2698 /// The reducing function is a closure with two arguments: an 'accumulator', and an element.
2699 /// For iterators with at least one element, this is the same as [`fold()`]
2700 /// with the first element of the iterator as the initial accumulator value, folding
2701 /// every subsequent element into it.
2702 ///
2703 /// [`fold()`]: Iterator::fold
2704 ///
2705 /// # Example
2706 ///
2707 /// ```
2708 /// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
2709 /// assert_eq!(reduced, 45);
2710 ///
2711 /// // Which is equivalent to doing it with `fold`:
2712 /// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
2713 /// assert_eq!(reduced, folded);
2714 /// ```
2715 #[inline]
2716 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2717 #[rustc_diagnostic_item = "iter_reduce"]
2718 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2719 where
2720 Self: Sized + [const] Destruct,
2721 F: [const] FnMut(Self::Item, Self::Item) -> Self::Item + [const] Destruct,
2722 {
2723 let first = self.next()?;
2724 Some(self.fold(first, f))
2725 }
2726
2727 /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the
2728 /// closure returns a failure, the failure is propagated back to the caller immediately.
2729 ///
2730 /// The return type of this method depends on the return type of the closure. If the closure
2731 /// returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>,
2732 /// E>`. If the closure returns `Option<Self::Item>`, then this function will return
2733 /// `Option<Option<Self::Item>>`.
2734 ///
2735 /// When called on an empty iterator, this function will return either `Some(None)` or
2736 /// `Ok(None)` depending on the type of the provided closure.
2737 ///
2738 /// For iterators with at least one element, this is essentially the same as calling
2739 /// [`try_fold()`] with the first element of the iterator as the initial accumulator value.
2740 ///
2741 /// [`try_fold()`]: Iterator::try_fold
2742 ///
2743 /// # Examples
2744 ///
2745 /// Safely calculate the sum of a series of numbers:
2746 ///
2747 /// ```
2748 /// #![feature(iterator_try_reduce)]
2749 ///
2750 /// let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];
2751 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2752 /// assert_eq!(sum, Some(Some(58)));
2753 /// ```
2754 ///
2755 /// Determine when a reduction short circuited:
2756 ///
2757 /// ```
2758 /// #![feature(iterator_try_reduce)]
2759 ///
2760 /// let numbers = vec![1, 2, 3, usize::MAX, 4, 5];
2761 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2762 /// assert_eq!(sum, None);
2763 /// ```
2764 ///
2765 /// Determine when a reduction was not performed because there are no elements:
2766 ///
2767 /// ```
2768 /// #![feature(iterator_try_reduce)]
2769 ///
2770 /// let numbers: Vec<usize> = Vec::new();
2771 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2772 /// assert_eq!(sum, Some(None));
2773 /// ```
2774 ///
2775 /// Use a [`Result`] instead of an [`Option`]:
2776 ///
2777 /// ```
2778 /// #![feature(iterator_try_reduce)]
2779 ///
2780 /// let numbers = vec!["1", "2", "3", "4", "5"];
2781 /// let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =
2782 /// numbers.into_iter().try_reduce(|x, y| {
2783 /// if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }
2784 /// });
2785 /// assert_eq!(max, Ok(Some("5")));
2786 /// ```
2787 #[inline]
2788 #[unstable(feature = "iterator_try_reduce", issue = "87053")]
2789 fn try_reduce<R>(
2790 &mut self,
2791 f: impl [const] FnMut(Self::Item, Self::Item) -> R + [const] Destruct,
2792 ) -> ChangeOutputType<R, Option<R::Output>>
2793 where
2794 Self: Sized,
2795 R: [const] Try<Output = Self::Item, Residual: [const] Residual<Option<Self::Item>>>,
2796 {
2797 let first = match self.next() {
2798 Some(i) => i,
2799 None => return Try::from_output(None),
2800 };
2801
2802 match self.try_fold(first, f).branch() {
2803 ControlFlow::Break(r) => FromResidual::from_residual(r),
2804 ControlFlow::Continue(i) => Try::from_output(Some(i)),
2805 }
2806 }
2807
2808 /// Tests if every element of the iterator matches a predicate.
2809 ///
2810 /// `all()` takes a closure that returns `true` or `false`. It applies
2811 /// this closure to each element of the iterator, and if they all return
2812 /// `true`, then so does `all()`. If any of them return `false`, it
2813 /// returns `false`.
2814 ///
2815 /// `all()` is short-circuiting; in other words, it will stop processing
2816 /// as soon as it finds a `false`, given that no matter what else happens,
2817 /// the result will also be `false`.
2818 ///
2819 /// An empty iterator returns `true`.
2820 ///
2821 /// # Examples
2822 ///
2823 /// Basic usage:
2824 ///
2825 /// ```
2826 /// let a = [1, 2, 3];
2827 ///
2828 /// assert!(a.into_iter().all(|x| x > 0));
2829 ///
2830 /// assert!(!a.into_iter().all(|x| x > 2));
2831 /// ```
2832 ///
2833 /// Stopping at the first `false`:
2834 ///
2835 /// ```
2836 /// let a = [1, 2, 3];
2837 ///
2838 /// let mut iter = a.into_iter();
2839 ///
2840 /// assert!(!iter.all(|x| x != 2));
2841 ///
2842 /// // we can still use `iter`, as there are more elements.
2843 /// assert_eq!(iter.next(), Some(3));
2844 /// ```
2845 #[inline]
2846 #[stable(feature = "rust1", since = "1.0.0")]
2847 #[rustc_diagnostic_item = "iter_all"]
2848 fn all<F>(&mut self, f: F) -> bool
2849 where
2850 Self: Sized,
2851 F: [const] FnMut(Self::Item) -> bool + [const] Destruct,
2852 {
2853 #[rustc_const_unstable(feature = "const_iter", issue = "92476")]
2854 #[inline]
2855 const fn check<T>(
2856 mut f: impl [const] FnMut(T) -> bool + [const] Destruct,
2857 ) -> impl [const] FnMut((), T) -> ControlFlow<()> + [const] Destruct {
2858 const move |(), x| {
2859 if f(x) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
2860 }
2861 }
2862 self.try_fold((), check(f)) == ControlFlow::Continue(())
2863 }
2864
2865 /// Tests if any element of the iterator matches a predicate.
2866 ///
2867 /// `any()` takes a closure that returns `true` or `false`. It applies
2868 /// this closure to each element of the iterator, and if any of them return
2869 /// `true`, then so does `any()`. If they all return `false`, it
2870 /// returns `false`.
2871 ///
2872 /// `any()` is short-circuiting; in other words, it will stop processing
2873 /// as soon as it finds a `true`, given that no matter what else happens,
2874 /// the result will also be `true`.
2875 ///
2876 /// An empty iterator returns `false`.
2877 ///
2878 /// # Examples
2879 ///
2880 /// Basic usage:
2881 ///
2882 /// ```
2883 /// let a = [1, 2, 3];
2884 ///
2885 /// assert!(a.into_iter().any(|x| x > 0));
2886 ///
2887 /// assert!(!a.into_iter().any(|x| x > 5));
2888 /// ```
2889 ///
2890 /// Stopping at the first `true`:
2891 ///
2892 /// ```
2893 /// let a = [1, 2, 3];
2894 ///
2895 /// let mut iter = a.into_iter();
2896 ///
2897 /// assert!(iter.any(|x| x != 2));
2898 ///
2899 /// // we can still use `iter`, as there are more elements.
2900 /// assert_eq!(iter.next(), Some(2));
2901 /// ```
2902 #[inline]
2903 #[stable(feature = "rust1", since = "1.0.0")]
2904 #[rustc_non_const_trait_method]
2905 #[rustc_diagnostic_item = "iter_any"]
2906 fn any<F>(&mut self, f: F) -> bool
2907 where
2908 Self: Sized,
2909 F: FnMut(Self::Item) -> bool,
2910 {
2911 #[inline]
2912 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2913 move |(), x| {
2914 if f(x) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
2915 }
2916 }
2917
2918 self.try_fold((), check(f)) == ControlFlow::Break(())
2919 }
2920
2921 /// Searches for an element of an iterator that satisfies a predicate.
2922 ///
2923 /// `find()` takes a closure that returns `true` or `false`. It applies
2924 /// this closure to each element of the iterator, and if any of them return
2925 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2926 /// `false`, it returns [`None`].
2927 ///
2928 /// `find()` is short-circuiting; in other words, it will stop processing
2929 /// as soon as the closure returns `true`.
2930 ///
2931 /// Because `find()` takes a reference, and many iterators iterate over
2932 /// references, this leads to a possibly confusing situation where the
2933 /// argument is a double reference. You can see this effect in the
2934 /// examples below, with `&&x`.
2935 ///
2936 /// If you need the index of the element, see [`position()`].
2937 ///
2938 /// [`Some(element)`]: Some
2939 /// [`position()`]: Iterator::position
2940 ///
2941 /// # Examples
2942 ///
2943 /// Basic usage:
2944 ///
2945 /// ```
2946 /// let a = [1, 2, 3];
2947 ///
2948 /// assert_eq!(a.into_iter().find(|&x| x == 2), Some(2));
2949 /// assert_eq!(a.into_iter().find(|&x| x == 5), None);
2950 /// ```
2951 ///
2952 /// Iterating over references:
2953 ///
2954 /// ```
2955 /// let a = [1, 2, 3];
2956 ///
2957 /// // `iter()` yields references i.e. `&i32` and `find()` takes a
2958 /// // reference to each element.
2959 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2960 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2961 /// ```
2962 ///
2963 /// Stopping at the first `true`:
2964 ///
2965 /// ```
2966 /// let a = [1, 2, 3];
2967 ///
2968 /// let mut iter = a.into_iter();
2969 ///
2970 /// assert_eq!(iter.find(|&x| x == 2), Some(2));
2971 ///
2972 /// // we can still use `iter`, as there are more elements.
2973 /// assert_eq!(iter.next(), Some(3));
2974 /// ```
2975 ///
2976 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2977 #[inline]
2978 #[stable(feature = "rust1", since = "1.0.0")]
2979 #[rustc_non_const_trait_method]
2980 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2981 where
2982 Self: Sized,
2983 P: FnMut(&Self::Item) -> bool,
2984 {
2985 #[inline]
2986 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2987 move |(), x| {
2988 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::Continue(()) }
2989 }
2990 }
2991
2992 self.try_fold((), check(predicate)).break_value()
2993 }
2994
2995 /// Applies function to the elements of iterator and returns
2996 /// the first non-none result.
2997 ///
2998 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2999 ///
3000 /// # Examples
3001 ///
3002 /// ```
3003 /// let a = ["lol", "NaN", "2", "5"];
3004 ///
3005 /// let first_number = a.iter().find_map(|s| s.parse().ok());
3006 ///
3007 /// assert_eq!(first_number, Some(2));
3008 /// ```
3009 #[inline]
3010 #[stable(feature = "iterator_find_map", since = "1.30.0")]
3011 #[rustc_non_const_trait_method]
3012 fn find_map<B, F>(&mut self, f: F) -> Option<B>
3013 where
3014 Self: Sized,
3015 F: FnMut(Self::Item) -> Option<B>,
3016 {
3017 #[inline]
3018 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
3019 move |(), x| match f(x) {
3020 Some(x) => ControlFlow::Break(x),
3021 None => ControlFlow::Continue(()),
3022 }
3023 }
3024
3025 self.try_fold((), check(f)).break_value()
3026 }
3027
3028 /// Applies function to the elements of iterator and returns
3029 /// the first true result or the first error.
3030 ///
3031 /// The return type of this method depends on the return type of the closure.
3032 /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.
3033 /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.
3034 ///
3035 /// # Examples
3036 ///
3037 /// ```
3038 /// #![feature(try_find)]
3039 ///
3040 /// let a = ["1", "2", "lol", "NaN", "5"];
3041 ///
3042 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
3043 /// Ok(s.parse::<i32>()? == search)
3044 /// };
3045 ///
3046 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 2));
3047 /// assert_eq!(result, Ok(Some("2")));
3048 ///
3049 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 5));
3050 /// assert!(result.is_err());
3051 /// ```
3052 ///
3053 /// This also supports other types which implement [`Try`], not just [`Result`].
3054 ///
3055 /// ```
3056 /// #![feature(try_find)]
3057 ///
3058 /// use std::num::NonZero;
3059 ///
3060 /// let a = [3, 5, 7, 4, 9, 0, 11u32];
3061 /// let result = a.into_iter().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3062 /// assert_eq!(result, Some(Some(4)));
3063 /// let result = a.into_iter().take(3).try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3064 /// assert_eq!(result, Some(None));
3065 /// let result = a.into_iter().rev().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3066 /// assert_eq!(result, None);
3067 /// ```
3068 #[inline]
3069 #[unstable(feature = "try_find", issue = "63178")]
3070 #[rustc_non_const_trait_method]
3071 fn try_find<R>(
3072 &mut self,
3073 f: impl FnMut(&Self::Item) -> R,
3074 ) -> ChangeOutputType<R, Option<Self::Item>>
3075 where
3076 Self: Sized,
3077 R: Try<Output = bool, Residual: Residual<Option<Self::Item>>>,
3078 {
3079 #[inline]
3080 fn check<I, V, R>(
3081 mut f: impl FnMut(&I) -> V,
3082 ) -> impl FnMut((), I) -> ControlFlow<R::TryType>
3083 where
3084 V: Try<Output = bool, Residual = R>,
3085 R: Residual<Option<I>>,
3086 {
3087 move |(), x| match f(&x).branch() {
3088 ControlFlow::Continue(false) => ControlFlow::Continue(()),
3089 ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),
3090 ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),
3091 }
3092 }
3093
3094 match self.try_fold((), check(f)) {
3095 ControlFlow::Break(x) => x,
3096 ControlFlow::Continue(()) => Try::from_output(None),
3097 }
3098 }
3099
3100 /// Searches for an element in an iterator, returning its index.
3101 ///
3102 /// `position()` takes a closure that returns `true` or `false`. It applies
3103 /// this closure to each element of the iterator, and if one of them
3104 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
3105 /// them return `false`, it returns [`None`].
3106 ///
3107 /// `position()` is short-circuiting; in other words, it will stop
3108 /// processing as soon as it finds a `true`.
3109 ///
3110 /// # Overflow Behavior
3111 ///
3112 /// The method does no guarding against overflows, so if there are more
3113 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
3114 /// result or panics. If overflow checks are enabled, a panic is
3115 /// guaranteed.
3116 ///
3117 /// # Panics
3118 ///
3119 /// This function might panic if the iterator has more than `usize::MAX`
3120 /// non-matching elements.
3121 ///
3122 /// [`Some(index)`]: Some
3123 ///
3124 /// # Examples
3125 ///
3126 /// Basic usage:
3127 ///
3128 /// ```
3129 /// let a = [1, 2, 3];
3130 ///
3131 /// assert_eq!(a.into_iter().position(|x| x == 2), Some(1));
3132 ///
3133 /// assert_eq!(a.into_iter().position(|x| x == 5), None);
3134 /// ```
3135 ///
3136 /// Stopping at the first `true`:
3137 ///
3138 /// ```
3139 /// let a = [1, 2, 3, 4];
3140 ///
3141 /// let mut iter = a.into_iter();
3142 ///
3143 /// assert_eq!(iter.position(|x| x >= 2), Some(1));
3144 ///
3145 /// // we can still use `iter`, as there are more elements.
3146 /// assert_eq!(iter.next(), Some(3));
3147 ///
3148 /// // The returned index depends on iterator state
3149 /// assert_eq!(iter.position(|x| x == 4), Some(0));
3150 ///
3151 /// ```
3152 #[inline]
3153 #[stable(feature = "rust1", since = "1.0.0")]
3154 #[rustc_non_const_trait_method]
3155 fn position<P>(&mut self, predicate: P) -> Option<usize>
3156 where
3157 Self: Sized,
3158 P: FnMut(Self::Item) -> bool,
3159 {
3160 #[inline]
3161 fn check<'a, T>(
3162 mut predicate: impl FnMut(T) -> bool + 'a,
3163 acc: &'a mut usize,
3164 ) -> impl FnMut((), T) -> ControlFlow<usize, ()> + 'a {
3165 #[rustc_inherit_overflow_checks]
3166 move |_, x| {
3167 if predicate(x) {
3168 ControlFlow::Break(*acc)
3169 } else {
3170 *acc += 1;
3171 ControlFlow::Continue(())
3172 }
3173 }
3174 }
3175
3176 let mut acc = 0;
3177 self.try_fold((), check(predicate, &mut acc)).break_value()
3178 }
3179
3180 /// Searches for an element in an iterator from the right, returning its
3181 /// index.
3182 ///
3183 /// `rposition()` takes a closure that returns `true` or `false`. It applies
3184 /// this closure to each element of the iterator, starting from the end,
3185 /// and if one of them returns `true`, then `rposition()` returns
3186 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
3187 ///
3188 /// `rposition()` is short-circuiting; in other words, it will stop
3189 /// processing as soon as it finds a `true`.
3190 ///
3191 /// [`Some(index)`]: Some
3192 ///
3193 /// # Examples
3194 ///
3195 /// Basic usage:
3196 ///
3197 /// ```
3198 /// let a = [1, 2, 3];
3199 ///
3200 /// assert_eq!(a.into_iter().rposition(|x| x == 3), Some(2));
3201 ///
3202 /// assert_eq!(a.into_iter().rposition(|x| x == 5), None);
3203 /// ```
3204 ///
3205 /// Stopping at the first `true`:
3206 ///
3207 /// ```
3208 /// let a = [-1, 2, 3, 4];
3209 ///
3210 /// let mut iter = a.into_iter();
3211 ///
3212 /// assert_eq!(iter.rposition(|x| x >= 2), Some(3));
3213 ///
3214 /// // we can still use `iter`, as there are more elements.
3215 /// assert_eq!(iter.next(), Some(-1));
3216 /// assert_eq!(iter.next_back(), Some(3));
3217 /// ```
3218 #[inline]
3219 #[stable(feature = "rust1", since = "1.0.0")]
3220 #[rustc_non_const_trait_method]
3221 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
3222 where
3223 P: FnMut(Self::Item) -> bool,
3224 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
3225 {
3226 // No need for an overflow check here, because `ExactSizeIterator`
3227 // implies that the number of elements fits into a `usize`.
3228 #[inline]
3229 fn check<T>(
3230 mut predicate: impl FnMut(T) -> bool,
3231 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
3232 move |i, x| {
3233 let i = i - 1;
3234 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
3235 }
3236 }
3237
3238 let n = self.len();
3239 self.try_rfold(n, check(predicate)).break_value()
3240 }
3241
3242 /// Returns the maximum element of an iterator.
3243 ///
3244 /// If several elements are equally maximum, the last element is
3245 /// returned. If the iterator is empty, [`None`] is returned.
3246 ///
3247 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3248 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3249 /// ```
3250 /// assert_eq!(
3251 /// [2.4, f32::NAN, 1.3]
3252 /// .into_iter()
3253 /// .reduce(f32::max)
3254 /// .unwrap_or(0.),
3255 /// 2.4
3256 /// );
3257 /// ```
3258 ///
3259 /// # Examples
3260 ///
3261 /// ```
3262 /// let a = [1, 2, 3];
3263 /// let b: [u32; 0] = [];
3264 ///
3265 /// assert_eq!(a.into_iter().max(), Some(3));
3266 /// assert_eq!(b.into_iter().max(), None);
3267 /// ```
3268 #[inline]
3269 #[stable(feature = "rust1", since = "1.0.0")]
3270 fn max(self) -> Option<Self::Item>
3271 where
3272 Self: Sized + [const] Destruct,
3273 Self::Item: [const] Ord + [const] Destruct,
3274 {
3275 self.reduce(Ord::max)
3276 }
3277
3278 /// Returns the minimum element of an iterator.
3279 ///
3280 /// If several elements are equally minimum, the first element is returned.
3281 /// If the iterator is empty, [`None`] is returned.
3282 ///
3283 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3284 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3285 /// ```
3286 /// assert_eq!(
3287 /// [2.4, f32::NAN, 1.3]
3288 /// .into_iter()
3289 /// .reduce(f32::min)
3290 /// .unwrap_or(0.),
3291 /// 1.3
3292 /// );
3293 /// ```
3294 ///
3295 /// # Examples
3296 ///
3297 /// ```
3298 /// let a = [1, 2, 3];
3299 /// let b: [u32; 0] = [];
3300 ///
3301 /// assert_eq!(a.into_iter().min(), Some(1));
3302 /// assert_eq!(b.into_iter().min(), None);
3303 /// ```
3304 #[inline]
3305 #[stable(feature = "rust1", since = "1.0.0")]
3306 fn min(self) -> Option<Self::Item>
3307 where
3308 Self: Sized + [const] Destruct,
3309 Self::Item: [const] Ord + [const] Destruct,
3310 {
3311 self.reduce(Ord::min)
3312 }
3313
3314 /// Returns the element that gives the maximum value from the
3315 /// specified function.
3316 ///
3317 /// If several elements are equally maximum, the last element is
3318 /// returned. If the iterator is empty, [`None`] is returned.
3319 ///
3320 /// # Examples
3321 ///
3322 /// ```
3323 /// let a = [-3_i32, 0, 1, 5, -10];
3324 /// assert_eq!(a.into_iter().max_by_key(|x| x.abs()).unwrap(), -10);
3325 /// ```
3326 #[inline]
3327 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3328 #[rustc_non_const_trait_method]
3329 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3330 where
3331 Self: Sized,
3332 F: FnMut(&Self::Item) -> B,
3333 {
3334 // If we implemented this via `max_by` that would force it to use `B::cmp`.
3335 // By using `max` over `KeyAndValue`, it instead ends up calling `B::lt`
3336 // (via `KeyAndValue::max`), which is often overridden more efficiently.
3337
3338 #[inline]
3339 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> KeyAndValue<B, T> {
3340 move |value| KeyAndValue { key: f(&value), value }
3341 }
3342
3343 let KeyAndValue { value, .. } = self.map(key(f)).max()?;
3344 Some(value)
3345 }
3346
3347 /// Returns the element that gives the maximum value with respect to the
3348 /// specified comparison function.
3349 ///
3350 /// If several elements are equally maximum, the last element is
3351 /// returned. If the iterator is empty, [`None`] is returned.
3352 ///
3353 /// # Examples
3354 ///
3355 /// ```
3356 /// let a = [-3_i32, 0, 1, 5, -10];
3357 /// assert_eq!(a.into_iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
3358 /// ```
3359 #[inline]
3360 #[stable(feature = "iter_max_by", since = "1.15.0")]
3361 fn max_by<F>(self, compare: F) -> Option<Self::Item>
3362 where
3363 Self: Sized + [const] Destruct,
3364 Self::Item: [const] Destruct,
3365 F: [const] FnMut(&Self::Item, &Self::Item) -> Ordering + [const] Destruct,
3366 {
3367 #[inline]
3368 #[rustc_const_unstable(feature = "const_iter", issue = "92476")]
3369 const fn fold<T>(
3370 mut compare: impl [const] FnMut(&T, &T) -> Ordering + [const] Destruct,
3371 ) -> impl [const] FnMut(T, T) -> T + [const] Destruct
3372 where
3373 T: [const] Destruct,
3374 {
3375 const move |x, y| cmp::max_by(x, y, &mut compare)
3376 }
3377
3378 self.reduce(fold(compare))
3379 }
3380
3381 /// Returns the element that gives the minimum value from the
3382 /// specified function.
3383 ///
3384 /// If several elements are equally minimum, the first element is
3385 /// returned. If the iterator is empty, [`None`] is returned.
3386 ///
3387 /// # Examples
3388 ///
3389 /// ```
3390 /// let a = [-3_i32, 0, 1, 5, -10];
3391 /// assert_eq!(a.into_iter().min_by_key(|x| x.abs()).unwrap(), 0);
3392 /// ```
3393 #[inline]
3394 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3395 #[rustc_non_const_trait_method]
3396 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3397 where
3398 Self: Sized,
3399 F: FnMut(&Self::Item) -> B,
3400 {
3401 // If we implemented this via `min_by` that would force it to use `B::cmp`.
3402 // By using `min` over `KeyAndValue`, it instead ends up calling `B::lt`
3403 // (via `KeyAndValue::min`), which is often overridden more efficiently.
3404
3405 #[inline]
3406 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> KeyAndValue<B, T> {
3407 move |value| KeyAndValue { key: f(&value), value }
3408 }
3409
3410 let KeyAndValue { value, .. } = self.map(key(f)).min()?;
3411 Some(value)
3412 }
3413
3414 /// Returns the element that gives the minimum value with respect to the
3415 /// specified comparison function.
3416 ///
3417 /// If several elements are equally minimum, the first element is
3418 /// returned. If the iterator is empty, [`None`] is returned.
3419 ///
3420 /// # Examples
3421 ///
3422 /// ```
3423 /// let a = [-3_i32, 0, 1, 5, -10];
3424 /// assert_eq!(a.into_iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
3425 /// ```
3426 #[inline]
3427 #[stable(feature = "iter_min_by", since = "1.15.0")]
3428 fn min_by<F>(self, compare: F) -> Option<Self::Item>
3429 where
3430 Self: Sized + [const] Destruct,
3431 F: [const] FnMut(&Self::Item, &Self::Item) -> Ordering + [const] Destruct,
3432 Self::Item: [const] Destruct,
3433 {
3434 #[inline]
3435 #[rustc_const_unstable(feature = "const_iter", issue = "92476")]
3436 const fn fold<T>(
3437 mut compare: impl [const] FnMut(&T, &T) -> Ordering + [const] Destruct,
3438 ) -> impl [const] FnMut(T, T) -> T + [const] Destruct
3439 where
3440 T: [const] Destruct,
3441 {
3442 const move |x, y| cmp::min_by(x, y, &mut compare)
3443 }
3444
3445 self.reduce(fold(compare))
3446 }
3447
3448 /// Reverses an iterator's direction.
3449 ///
3450 /// Usually, iterators iterate from left to right. After using `rev()`,
3451 /// an iterator will instead iterate from right to left.
3452 ///
3453 /// This is only possible if the iterator has an end, so `rev()` only
3454 /// works on [`DoubleEndedIterator`]s.
3455 ///
3456 /// # Examples
3457 ///
3458 /// ```
3459 /// let a = [1, 2, 3];
3460 ///
3461 /// let mut iter = a.into_iter().rev();
3462 ///
3463 /// assert_eq!(iter.next(), Some(3));
3464 /// assert_eq!(iter.next(), Some(2));
3465 /// assert_eq!(iter.next(), Some(1));
3466 ///
3467 /// assert_eq!(iter.next(), None);
3468 /// ```
3469 #[inline]
3470 #[doc(alias = "reverse")]
3471 #[stable(feature = "rust1", since = "1.0.0")]
3472 fn rev(self) -> Rev<Self>
3473 where
3474 Self: Sized + DoubleEndedIterator,
3475 {
3476 Rev::new(self)
3477 }
3478
3479 /// Converts an iterator of pairs into a pair of containers.
3480 ///
3481 /// `unzip()` consumes an entire iterator of pairs, producing two
3482 /// collections: one from the left elements of the pairs, and one
3483 /// from the right elements.
3484 ///
3485 /// This function is, in some sense, the opposite of [`zip`].
3486 ///
3487 /// [`zip`]: Iterator::zip
3488 ///
3489 /// # Examples
3490 ///
3491 /// ```
3492 /// let a = [(1, 2), (3, 4), (5, 6)];
3493 ///
3494 /// let (left, right): (Vec<_>, Vec<_>) = a.into_iter().unzip();
3495 ///
3496 /// assert_eq!(left, [1, 3, 5]);
3497 /// assert_eq!(right, [2, 4, 6]);
3498 ///
3499 /// // you can also unzip multiple nested tuples at once
3500 /// let a = [(1, (2, 3)), (4, (5, 6))];
3501 ///
3502 /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.into_iter().unzip();
3503 /// assert_eq!(x, [1, 4]);
3504 /// assert_eq!(y, [2, 5]);
3505 /// assert_eq!(z, [3, 6]);
3506 /// ```
3507 #[stable(feature = "rust1", since = "1.0.0")]
3508 #[rustc_non_const_trait_method]
3509 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
3510 where
3511 FromA: Default + Extend<A>,
3512 FromB: Default + Extend<B>,
3513 Self: Sized + Iterator<Item = (A, B)>,
3514 {
3515 let mut unzipped: (FromA, FromB) = Default::default();
3516 unzipped.extend(self);
3517 unzipped
3518 }
3519
3520 /// Creates an iterator which copies all of its elements.
3521 ///
3522 /// This is useful when you have an iterator over `&T`, but you need an
3523 /// iterator over `T`.
3524 ///
3525 /// # Examples
3526 ///
3527 /// ```
3528 /// let a = [1, 2, 3];
3529 ///
3530 /// let v_copied: Vec<_> = a.iter().copied().collect();
3531 ///
3532 /// // copied is the same as .map(|&x| x)
3533 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3534 ///
3535 /// assert_eq!(v_copied, [1, 2, 3]);
3536 /// assert_eq!(v_map, [1, 2, 3]);
3537 /// ```
3538 #[stable(feature = "iter_copied", since = "1.36.0")]
3539 #[rustc_diagnostic_item = "iter_copied"]
3540 fn copied<'a, T>(self) -> Copied<Self>
3541 where
3542 T: Copy + 'a,
3543 Self: Sized + Iterator<Item = &'a T>,
3544 {
3545 Copied::new(self)
3546 }
3547
3548 /// Creates an iterator which [`clone`]s all of its elements.
3549 ///
3550 /// This is useful when you have an iterator over `&T`, but you need an
3551 /// iterator over `T`.
3552 ///
3553 /// There is no guarantee whatsoever about the `clone` method actually
3554 /// being called *or* optimized away. So code should not depend on
3555 /// either.
3556 ///
3557 /// [`clone`]: Clone::clone
3558 ///
3559 /// # Examples
3560 ///
3561 /// Basic usage:
3562 ///
3563 /// ```
3564 /// let a = [1, 2, 3];
3565 ///
3566 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
3567 ///
3568 /// // cloned is the same as .map(|&x| x), for integers
3569 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3570 ///
3571 /// assert_eq!(v_cloned, [1, 2, 3]);
3572 /// assert_eq!(v_map, [1, 2, 3]);
3573 /// ```
3574 ///
3575 /// To get the best performance, try to clone late:
3576 ///
3577 /// ```
3578 /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3579 /// // don't do this:
3580 /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3581 /// assert_eq!(&[vec![23]], &slower[..]);
3582 /// // instead call `cloned` late
3583 /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3584 /// assert_eq!(&[vec![23]], &faster[..]);
3585 /// ```
3586 #[stable(feature = "rust1", since = "1.0.0")]
3587 #[rustc_diagnostic_item = "iter_cloned"]
3588 fn cloned<'a, T>(self) -> Cloned<Self>
3589 where
3590 T: Clone + 'a,
3591 Self: Sized + Iterator<Item = &'a T>,
3592 {
3593 Cloned::new(self)
3594 }
3595
3596 /// Repeats an iterator endlessly.
3597 ///
3598 /// Instead of stopping at [`None`], the iterator will instead start again,
3599 /// from the beginning. After iterating again, it will start at the
3600 /// beginning again. And again. And again. Forever. Note that in case the
3601 /// original iterator is empty, the resulting iterator will also be empty.
3602 ///
3603 /// # Examples
3604 ///
3605 /// ```
3606 /// let a = [1, 2, 3];
3607 ///
3608 /// let mut iter = a.into_iter().cycle();
3609 ///
3610 /// loop {
3611 /// assert_eq!(iter.next(), Some(1));
3612 /// assert_eq!(iter.next(), Some(2));
3613 /// assert_eq!(iter.next(), Some(3));
3614 /// # break;
3615 /// }
3616 /// ```
3617 #[stable(feature = "rust1", since = "1.0.0")]
3618 #[inline]
3619 #[rustc_diagnostic_item = "iter_cycle"]
3620 fn cycle(self) -> Cycle<Self>
3621 where
3622 Self: Sized + [const] Clone,
3623 {
3624 Cycle::new(self)
3625 }
3626
3627 /// Returns an iterator over `N` elements of the iterator at a time.
3628 ///
3629 /// The chunks do not overlap. If `N` does not divide the length of the
3630 /// iterator, then the last up to `N-1` elements will be omitted and can be
3631 /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]
3632 /// function of the iterator.
3633 ///
3634 /// # Panics
3635 ///
3636 /// Panics if `N` is zero.
3637 ///
3638 /// # Examples
3639 ///
3640 /// Basic usage:
3641 ///
3642 /// ```
3643 /// #![feature(iter_array_chunks)]
3644 ///
3645 /// let mut iter = "lorem".chars().array_chunks();
3646 /// assert_eq!(iter.next(), Some(['l', 'o']));
3647 /// assert_eq!(iter.next(), Some(['r', 'e']));
3648 /// assert_eq!(iter.next(), None);
3649 /// assert_eq!(iter.into_remainder().as_slice(), &['m']);
3650 /// ```
3651 ///
3652 /// ```
3653 /// #![feature(iter_array_chunks)]
3654 ///
3655 /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
3656 /// // ^-----^ ^------^
3657 /// for [x, y, z] in data.iter().array_chunks() {
3658 /// assert_eq!(x + y + z, 4);
3659 /// }
3660 /// ```
3661 #[track_caller]
3662 #[unstable(feature = "iter_array_chunks", issue = "100450")]
3663 #[rustc_diagnostic_item = "iter_array_chunks"]
3664 fn array_chunks<#[lint::panics_when_zero] const N: usize>(self) -> ArrayChunks<Self, N>
3665 where
3666 Self: Sized,
3667 {
3668 ArrayChunks::new(self)
3669 }
3670
3671 /// Sums the elements of an iterator.
3672 ///
3673 /// Takes each element, adds them together, and returns the result.
3674 ///
3675 /// An empty iterator returns the *additive identity* ("zero") of the type,
3676 /// which is `0` for integers and `-0.0` for floats.
3677 ///
3678 /// `sum()` can be used to sum any type implementing [`Sum`][`core::iter::Sum`],
3679 /// including [`Option`][`Option::sum`] and [`Result`][`Result::sum`].
3680 ///
3681 /// # Panics
3682 ///
3683 /// When calling `sum()` and a primitive integer type is being returned, this
3684 /// method will panic if the computation overflows and overflow checks are
3685 /// enabled.
3686 ///
3687 /// # Examples
3688 ///
3689 /// ```
3690 /// let a = [1, 2, 3];
3691 /// let sum: i32 = a.iter().sum();
3692 ///
3693 /// assert_eq!(sum, 6);
3694 ///
3695 /// let b: Vec<f32> = vec![];
3696 /// let sum: f32 = b.iter().sum();
3697 /// assert_eq!(sum, -0.0_f32);
3698 /// ```
3699 #[stable(feature = "iter_arith", since = "1.11.0")]
3700 #[rustc_diagnostic_item = "iter_sum"]
3701 fn sum<S>(self) -> S
3702 where
3703 Self: Sized,
3704 S: [const] Sum<Self::Item>,
3705 {
3706 Sum::sum(self)
3707 }
3708
3709 /// Iterates over the entire iterator, multiplying all the elements.
3710 ///
3711 /// An empty iterator returns the one value of the type.
3712 ///
3713 /// `product()` can be used to multiply any type implementing [`Product`][`core::iter::Product`],
3714 /// including [`Option`][`Option::product`] and [`Result`][`Result::product`].
3715 ///
3716 /// # Panics
3717 ///
3718 /// When calling `product()` and a primitive integer type is being returned,
3719 /// method will panic if the computation overflows and overflow checks are
3720 /// enabled.
3721 ///
3722 /// # Examples
3723 ///
3724 /// ```
3725 /// fn factorial(n: u32) -> u32 {
3726 /// (1..=n).product()
3727 /// }
3728 /// assert_eq!(factorial(0), 1);
3729 /// assert_eq!(factorial(1), 1);
3730 /// assert_eq!(factorial(5), 120);
3731 /// ```
3732 #[stable(feature = "iter_arith", since = "1.11.0")]
3733 #[rustc_diagnostic_item = "iter_product"]
3734 fn product<P>(self) -> P
3735 where
3736 Self: Sized,
3737 P: [const] Product<Self::Item>,
3738 {
3739 Product::product(self)
3740 }
3741
3742 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3743 /// of another.
3744 ///
3745 /// # Examples
3746 ///
3747 /// ```
3748 /// use std::cmp::Ordering;
3749 ///
3750 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3751 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3752 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3753 /// ```
3754 #[stable(feature = "iter_order", since = "1.5.0")]
3755 #[rustc_non_const_trait_method]
3756 fn cmp<I>(self, other: I) -> Ordering
3757 where
3758 I: IntoIterator<Item = Self::Item>,
3759 Self::Item: Ord,
3760 Self: Sized,
3761 {
3762 self.cmp_by(other, |x, y| x.cmp(&y))
3763 }
3764
3765 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3766 /// of another with respect to the specified comparison function.
3767 ///
3768 /// # Examples
3769 ///
3770 /// ```
3771 /// #![feature(iter_order_by)]
3772 ///
3773 /// use std::cmp::Ordering;
3774 ///
3775 /// let xs = [1, 2, 3, 4];
3776 /// let ys = [1, 4, 9, 16];
3777 ///
3778 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| x.cmp(&y)), Ordering::Less);
3779 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (x * x).cmp(&y)), Ordering::Equal);
3780 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (2 * x).cmp(&y)), Ordering::Greater);
3781 /// ```
3782 #[unstable(feature = "iter_order_by", issue = "64295")]
3783 #[rustc_non_const_trait_method]
3784 fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
3785 where
3786 Self: Sized,
3787 I: IntoIterator,
3788 F: FnMut(Self::Item, I::Item) -> Ordering,
3789 {
3790 #[inline]
3791 fn compare<X, Y, F>(mut cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Ordering>
3792 where
3793 F: FnMut(X, Y) -> Ordering,
3794 {
3795 move |x, y| match cmp(x, y) {
3796 Ordering::Equal => ControlFlow::Continue(()),
3797 non_eq => ControlFlow::Break(non_eq),
3798 }
3799 }
3800
3801 match iter_compare(self, other.into_iter(), compare(cmp)) {
3802 ControlFlow::Continue(ord) => ord,
3803 ControlFlow::Break(ord) => ord,
3804 }
3805 }
3806
3807 /// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of
3808 /// this [`Iterator`] with those of another. The comparison works like short-circuit
3809 /// evaluation, returning a result without comparing the remaining elements.
3810 /// As soon as an order can be determined, the evaluation stops and a result is returned.
3811 ///
3812 /// # Examples
3813 ///
3814 /// ```
3815 /// use std::cmp::Ordering;
3816 ///
3817 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3818 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3819 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3820 /// ```
3821 ///
3822 /// For floating-point numbers, NaN does not have a total order and will result
3823 /// in `None` when compared:
3824 ///
3825 /// ```
3826 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3827 /// ```
3828 ///
3829 /// The results are determined by the order of evaluation.
3830 ///
3831 /// ```
3832 /// use std::cmp::Ordering;
3833 ///
3834 /// assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less));
3835 /// assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater));
3836 /// assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None);
3837 /// ```
3838 ///
3839 #[stable(feature = "iter_order", since = "1.5.0")]
3840 #[rustc_non_const_trait_method]
3841 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3842 where
3843 I: IntoIterator,
3844 Self::Item: PartialOrd<I::Item>,
3845 Self: Sized,
3846 {
3847 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3848 }
3849
3850 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3851 /// of another with respect to the specified comparison function.
3852 ///
3853 /// # Examples
3854 ///
3855 /// ```
3856 /// #![feature(iter_order_by)]
3857 ///
3858 /// use std::cmp::Ordering;
3859 ///
3860 /// let xs = [1.0, 2.0, 3.0, 4.0];
3861 /// let ys = [1.0, 4.0, 9.0, 16.0];
3862 ///
3863 /// assert_eq!(
3864 /// xs.iter().partial_cmp_by(ys, |x, y| x.partial_cmp(&y)),
3865 /// Some(Ordering::Less)
3866 /// );
3867 /// assert_eq!(
3868 /// xs.iter().partial_cmp_by(ys, |x, y| (x * x).partial_cmp(&y)),
3869 /// Some(Ordering::Equal)
3870 /// );
3871 /// assert_eq!(
3872 /// xs.iter().partial_cmp_by(ys, |x, y| (2.0 * x).partial_cmp(&y)),
3873 /// Some(Ordering::Greater)
3874 /// );
3875 /// ```
3876 #[unstable(feature = "iter_order_by", issue = "64295")]
3877 #[rustc_non_const_trait_method]
3878 fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
3879 where
3880 Self: Sized,
3881 I: IntoIterator,
3882 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3883 {
3884 #[inline]
3885 fn compare<X, Y, F>(mut partial_cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Option<Ordering>>
3886 where
3887 F: FnMut(X, Y) -> Option<Ordering>,
3888 {
3889 move |x, y| match partial_cmp(x, y) {
3890 Some(Ordering::Equal) => ControlFlow::Continue(()),
3891 non_eq => ControlFlow::Break(non_eq),
3892 }
3893 }
3894
3895 match iter_compare(self, other.into_iter(), compare(partial_cmp)) {
3896 ControlFlow::Continue(ord) => Some(ord),
3897 ControlFlow::Break(ord) => ord,
3898 }
3899 }
3900
3901 /// Determines if the elements of this [`Iterator`] are equal to those of
3902 /// another.
3903 ///
3904 /// # Examples
3905 ///
3906 /// ```
3907 /// assert_eq!([1].iter().eq([1].iter()), true);
3908 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3909 /// ```
3910 #[stable(feature = "iter_order", since = "1.5.0")]
3911 #[rustc_non_const_trait_method]
3912 fn eq<I>(self, other: I) -> bool
3913 where
3914 I: IntoIterator,
3915 Self::Item: PartialEq<I::Item>,
3916 Self: Sized,
3917 {
3918 self.eq_by(other, |x, y| x == y)
3919 }
3920
3921 /// Determines if the elements of this [`Iterator`] are equal to those of
3922 /// another with respect to the specified equality function.
3923 ///
3924 /// # Examples
3925 ///
3926 /// ```
3927 /// #![feature(iter_order_by)]
3928 ///
3929 /// let xs = [1, 2, 3, 4];
3930 /// let ys = [1, 4, 9, 16];
3931 ///
3932 /// assert!(xs.iter().eq_by(ys, |x, y| x * x == y));
3933 /// ```
3934 #[unstable(feature = "iter_order_by", issue = "64295")]
3935 #[rustc_non_const_trait_method]
3936 fn eq_by<I, F>(self, other: I, eq: F) -> bool
3937 where
3938 Self: Sized,
3939 I: IntoIterator,
3940 F: FnMut(Self::Item, I::Item) -> bool,
3941 {
3942 #[inline]
3943 fn compare<X, Y, F>(mut eq: F) -> impl FnMut(X, Y) -> ControlFlow<()>
3944 where
3945 F: FnMut(X, Y) -> bool,
3946 {
3947 move |x, y| {
3948 if eq(x, y) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
3949 }
3950 }
3951
3952 SpecIterEq::spec_iter_eq(self, other.into_iter(), compare(eq))
3953 }
3954
3955 /// Determines if the elements of this [`Iterator`] are not equal to those of
3956 /// another.
3957 ///
3958 /// # Examples
3959 ///
3960 /// ```
3961 /// assert_eq!([1].iter().ne([1].iter()), false);
3962 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3963 /// ```
3964 #[stable(feature = "iter_order", since = "1.5.0")]
3965 #[rustc_non_const_trait_method]
3966 fn ne<I>(self, other: I) -> bool
3967 where
3968 I: IntoIterator,
3969 Self::Item: PartialEq<I::Item>,
3970 Self: Sized,
3971 {
3972 !self.eq(other)
3973 }
3974
3975 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3976 /// less than those of another.
3977 ///
3978 /// # Examples
3979 ///
3980 /// ```
3981 /// assert_eq!([1].iter().lt([1].iter()), false);
3982 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3983 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3984 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3985 /// ```
3986 #[stable(feature = "iter_order", since = "1.5.0")]
3987 #[rustc_non_const_trait_method]
3988 fn lt<I>(self, other: I) -> bool
3989 where
3990 I: IntoIterator,
3991 Self::Item: PartialOrd<I::Item>,
3992 Self: Sized,
3993 {
3994 self.partial_cmp(other) == Some(Ordering::Less)
3995 }
3996
3997 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3998 /// less or equal to those of another.
3999 ///
4000 /// # Examples
4001 ///
4002 /// ```
4003 /// assert_eq!([1].iter().le([1].iter()), true);
4004 /// assert_eq!([1].iter().le([1, 2].iter()), true);
4005 /// assert_eq!([1, 2].iter().le([1].iter()), false);
4006 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
4007 /// ```
4008 #[stable(feature = "iter_order", since = "1.5.0")]
4009 #[rustc_non_const_trait_method]
4010 fn le<I>(self, other: I) -> bool
4011 where
4012 I: IntoIterator,
4013 Self::Item: PartialOrd<I::Item>,
4014 Self: Sized,
4015 {
4016 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
4017 }
4018
4019 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
4020 /// greater than those of another.
4021 ///
4022 /// # Examples
4023 ///
4024 /// ```
4025 /// assert_eq!([1].iter().gt([1].iter()), false);
4026 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
4027 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
4028 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
4029 /// ```
4030 #[stable(feature = "iter_order", since = "1.5.0")]
4031 #[rustc_non_const_trait_method]
4032 fn gt<I>(self, other: I) -> bool
4033 where
4034 I: IntoIterator,
4035 Self::Item: PartialOrd<I::Item>,
4036 Self: Sized,
4037 {
4038 self.partial_cmp(other) == Some(Ordering::Greater)
4039 }
4040
4041 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
4042 /// greater than or equal to those of another.
4043 ///
4044 /// # Examples
4045 ///
4046 /// ```
4047 /// assert_eq!([1].iter().ge([1].iter()), true);
4048 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
4049 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
4050 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
4051 /// ```
4052 #[stable(feature = "iter_order", since = "1.5.0")]
4053 #[rustc_non_const_trait_method]
4054 fn ge<I>(self, other: I) -> bool
4055 where
4056 I: IntoIterator,
4057 Self::Item: PartialOrd<I::Item>,
4058 Self: Sized,
4059 {
4060 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
4061 }
4062
4063 /// Checks if the elements of this iterator are sorted.
4064 ///
4065 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
4066 /// iterator yields exactly zero or one element, `true` is returned.
4067 ///
4068 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
4069 /// implies that this function returns `false` if any two consecutive items are not
4070 /// comparable.
4071 ///
4072 /// # Examples
4073 ///
4074 /// ```
4075 /// assert!([1, 2, 2, 9].iter().is_sorted());
4076 /// assert!(![1, 3, 2, 4].iter().is_sorted());
4077 /// assert!([0].iter().is_sorted());
4078 /// assert!(std::iter::empty::<i32>().is_sorted());
4079 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
4080 /// ```
4081 #[inline]
4082 #[stable(feature = "is_sorted", since = "1.82.0")]
4083 fn is_sorted(self) -> bool
4084 where
4085 Self: Sized + [const] Destruct,
4086 Self::Item: [const] PartialOrd + [const] Destruct,
4087 {
4088 self.is_sorted_by(const |a, b| a <= b)
4089 }
4090
4091 /// Checks if the elements of this iterator are sorted using the given comparator function.
4092 ///
4093 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4094 /// function to determine whether two elements are to be considered in sorted order.
4095 ///
4096 /// # Examples
4097 ///
4098 /// ```
4099 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b));
4100 /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b));
4101 ///
4102 /// assert!([0].iter().is_sorted_by(|a, b| true));
4103 /// assert!([0].iter().is_sorted_by(|a, b| false));
4104 ///
4105 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| false));
4106 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| true));
4107 /// ```
4108 #[stable(feature = "is_sorted", since = "1.82.0")]
4109 fn is_sorted_by<F>(mut self, compare: F) -> bool
4110 where
4111 Self: Sized + [const] Destruct,
4112 Self::Item: [const] Destruct,
4113 F: [const] FnMut(&Self::Item, &Self::Item) -> bool + [const] Destruct,
4114 {
4115 #[inline]
4116 #[rustc_const_unstable(feature = "const_iter", issue = "92476")]
4117 const fn check<'a, T>(
4118 last: &'a mut T,
4119 mut compare: impl [const] FnMut(&T, &T) -> bool + 'a + [const] Destruct,
4120 ) -> impl [const] FnMut(T) -> bool + 'a + [const] Destruct
4121 where
4122 T: [const] Destruct,
4123 {
4124 const move |curr| {
4125 if !compare(last, &curr) {
4126 return false;
4127 }
4128 *last = curr;
4129 true
4130 }
4131 }
4132
4133 let mut last = match self.next() {
4134 Some(e) => e,
4135 None => return true,
4136 };
4137
4138 self.all(check(&mut last, compare))
4139 }
4140
4141 /// Checks if the elements of this iterator are sorted using the given key extraction
4142 /// function.
4143 ///
4144 /// Instead of comparing the iterator's elements directly, this function compares the keys of
4145 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
4146 /// its documentation for more information.
4147 ///
4148 /// [`is_sorted`]: Iterator::is_sorted
4149 ///
4150 /// # Examples
4151 ///
4152 /// ```
4153 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
4154 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
4155 /// ```
4156 #[inline]
4157 #[stable(feature = "is_sorted", since = "1.82.0")]
4158 #[rustc_non_const_trait_method]
4159 fn is_sorted_by_key<F, K>(self, f: F) -> bool
4160 where
4161 Self: Sized,
4162 F: FnMut(Self::Item) -> K,
4163 K: PartialOrd,
4164 {
4165 self.map(f).is_sorted()
4166 }
4167
4168 /// See [TrustedRandomAccess][super::super::TrustedRandomAccess]
4169 // The unusual name is to avoid name collisions in method resolution
4170 // see #76479.
4171 #[inline]
4172 #[doc(hidden)]
4173 #[unstable(feature = "trusted_random_access", issue = "none")]
4174 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
4175 where
4176 Self: TrustedRandomAccessNoCoerce,
4177 {
4178 // Always specialized
4179 unreachable!();
4180 }
4181}
4182
4183trait SpecIterEq<B: Iterator>: Iterator {
4184 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4185 where
4186 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>;
4187}
4188
4189impl<A: Iterator, B: Iterator> SpecIterEq<B> for A {
4190 #[inline]
4191 default fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4192 where
4193 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4194 {
4195 iter_eq(self, b, f)
4196 }
4197}
4198
4199impl<A: Iterator + TrustedLen, B: Iterator + TrustedLen> SpecIterEq<B> for A {
4200 #[inline]
4201 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4202 where
4203 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4204 {
4205 // we *can't* short-circuit if:
4206 match (self.size_hint(), b.size_hint()) {
4207 // ... both iterators have the same length
4208 ((_, Some(a)), (_, Some(b))) if a == b => {}
4209 // ... or both of them are longer than `usize::MAX` (i.e. have an unknown length).
4210 ((_, None), (_, None)) => {}
4211 // otherwise, we can ascertain that they are unequal without actually comparing items
4212 _ => return false,
4213 }
4214
4215 iter_eq(self, b, f)
4216 }
4217}
4218
4219/// Compares two iterators element-wise using the given function.
4220///
4221/// If `ControlFlow::Continue(())` is returned from the function, the comparison moves on to the next
4222/// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and
4223/// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,
4224/// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of
4225/// the iterators.
4226///
4227/// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),
4228/// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).
4229#[inline]
4230fn iter_compare<A, B, F, T>(mut a: A, mut b: B, f: F) -> ControlFlow<T, Ordering>
4231where
4232 A: Iterator,
4233 B: Iterator,
4234 F: FnMut(A::Item, B::Item) -> ControlFlow<T>,
4235{
4236 #[inline]
4237 fn compare<'a, B, X, T>(
4238 b: &'a mut B,
4239 mut f: impl FnMut(X, B::Item) -> ControlFlow<T> + 'a,
4240 ) -> impl FnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> + 'a
4241 where
4242 B: Iterator,
4243 {
4244 move |x| match b.next() {
4245 None => ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),
4246 Some(y) => f(x, y).map_break(ControlFlow::Break),
4247 }
4248 }
4249
4250 match a.try_for_each(compare(&mut b, f)) {
4251 ControlFlow::Continue(()) => ControlFlow::Continue(match b.next() {
4252 None => Ordering::Equal,
4253 Some(_) => Ordering::Less,
4254 }),
4255 ControlFlow::Break(x) => x,
4256 }
4257}
4258
4259#[inline]
4260fn iter_eq<A, B, F>(a: A, b: B, f: F) -> bool
4261where
4262 A: Iterator,
4263 B: Iterator,
4264 F: FnMut(A::Item, B::Item) -> ControlFlow<()>,
4265{
4266 iter_compare(a, b, f).continue_value().is_some_and(|ord| ord == Ordering::Equal)
4267}
4268
4269/// Implements `Iterator` for mutable references to iterators, such as those produced by [`Iterator::by_ref`].
4270///
4271/// This implementation passes all method calls on to the original iterator.
4272#[stable(feature = "rust1", since = "1.0.0")]
4273impl<I: Iterator + ?Sized> Iterator for &mut I {
4274 type Item = I::Item;
4275 #[inline]
4276 fn next(&mut self) -> Option<I::Item> {
4277 (**self).next()
4278 }
4279 fn size_hint(&self) -> (usize, Option<usize>) {
4280 (**self).size_hint()
4281 }
4282 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
4283 (**self).advance_by(n)
4284 }
4285 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4286 (**self).nth(n)
4287 }
4288 fn fold<B, F>(self, init: B, f: F) -> B
4289 where
4290 F: FnMut(B, Self::Item) -> B,
4291 {
4292 self.spec_fold(init, f)
4293 }
4294 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4295 where
4296 F: FnMut(B, Self::Item) -> R,
4297 R: Try<Output = B>,
4298 {
4299 self.spec_try_fold(init, f)
4300 }
4301}
4302
4303/// Helper trait to specialize `fold` and `try_fold` for `&mut I where I: Sized`
4304trait IteratorRefSpec: Iterator {
4305 fn spec_fold<B, F>(self, init: B, f: F) -> B
4306 where
4307 F: FnMut(B, Self::Item) -> B;
4308
4309 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4310 where
4311 F: FnMut(B, Self::Item) -> R,
4312 R: Try<Output = B>;
4313}
4314
4315impl<I: Iterator + ?Sized> IteratorRefSpec for &mut I {
4316 default fn spec_fold<B, F>(self, init: B, mut f: F) -> B
4317 where
4318 F: FnMut(B, Self::Item) -> B,
4319 {
4320 let mut accum = init;
4321 while let Some(x) = self.next() {
4322 accum = f(accum, x);
4323 }
4324 accum
4325 }
4326
4327 default fn spec_try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
4328 where
4329 F: FnMut(B, Self::Item) -> R,
4330 R: Try<Output = B>,
4331 {
4332 let mut accum = init;
4333 while let Some(x) = self.next() {
4334 accum = f(accum, x)?;
4335 }
4336 try { accum }
4337 }
4338}
4339
4340impl<I: Iterator> IteratorRefSpec for &mut I {
4341 impl_fold_via_try_fold! { spec_fold -> spec_try_fold }
4342
4343 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4344 where
4345 F: FnMut(B, Self::Item) -> R,
4346 R: Try<Output = B>,
4347 {
4348 (**self).try_fold(init, f)
4349 }
4350}